在配置Spring Security中,可能会出现AntMatcher与表单登录冲突的问题。此时需要在AntMatcher中添加.excludePathPatterns()方法来排除表单登录的路径。
示例代码:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/login**").permitAll()
.antMatchers("/api/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/dashboard")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.permitAll();
http.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER")
.and()
.withUser("admin")
.password("{noop}password")
.roles("ADMIN");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
}
在代码中,可以使用.excludePathPatterns()方法 来排除表单登录的请求路径,示例如下:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**")
.and()
.ignoring()
.antMatchers("/login", "/login**", "/login*", "/auth/**", "/login/login*")
.and()
.ignoring()
.antMatchers("/api/**");
}