以 configure(HttpSecurity http) 方法为例,可以展示如何配置及其在方法内部调用的方法的作用。 首先,在 Spring Security 的配置类中,需要重写 configure(HttpSecurity http) 方法:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
在上述代码中,首先通过 authorizeRequests() 方法开始配置请求的授权方式,通过 antMatchers() 方法指定不需要认证的路径,通过 anyRequest() 方法指定其他请求需要认证。 接下来,通过 formLogin() 方法配置登录页面的路径,permitAll() 方法指定该路径不需要身份认证。 最后,通过 logout() 方法配置退出登录的路径,同样指定该路径不需要身份认证。 在 configure(HttpSecurity http) 方法中,还可以调用其他方法,如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private CustomAuthenticationSuccessHandler successHandler;
@Autowired
private CustomAuthenticationFailureHandler failureHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.successHandler(successHandler)
.failureHandler(failureHandler)
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.rememberMe()
.userDetailsService(userDetailsService)
.tokenValiditySeconds(86400)
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/login?expired");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
在上述代码中,首先通过 @Autowired 注解注入了自定义的 UserDetailsService、AuthenticationSuccessHandler 和 AuthenticationFailureHandler。 在 configure(HttpSecurity http) 方法中,通过 successHandler() 和 failureHandler() 方法配置登录成功和失败的处理器,实现自定义登录逻辑。 接下来,通过 exceptionHandling() 方法配置异常处理方式,如访问被拒绝的页面、认证失败等情况的处理。 通过 rememberMe() 方法配置记住我功能的实现方式,指定了 UserDetailsService 和 token 的有效期。 最后,通过 sessionManagement() 方法配置会话管理的方式,指定了会话的最大数量和过期时间。 在 configureGlobal(AuthenticationManagerBuilder auth) 方法中,通过 userDetailsService() 方法指定了自定义的 UserDetailsService 实现类,并通过 passwordEncoder() 方法指定了密码的加密方式。