1、简介
- 在Spring Security中,WebSecurityConfigurerAdapter类是一个配置适配器,它提供了多种configure方法的重载,允许开发者以声明性的方式配置Web安全。
2、相关规则
1. configure(WebSecurity web)
 
此方法用于配置哪些请求应该被Spring Security的过滤器链忽略。这通常用于静态资源(如CSS、JS、图片等),这些资源不需要进行安全认证。
@Override  
public void configure(WebSecurity web) throws Exception {  web.ignoring()  .antMatchers("/css/**", "/js/**", "/images/**", "/favicon.ico");  
}2. configure(HttpSecurity http)
 
这是 WebSecurityConfigurerAdapter 中最重要的 configure 方法之一,它用于配置HTTP安全。通过这个方法,你可以定义哪些URL模式需要被保护,以及如何进行身份验证和授权。
@Override  
protected void configure(HttpSecurity http) throws Exception {  http  // 启用CSRF保护  .csrf().disable() // 注意:出于示例目的,这里禁用了CSRF保护,实际项目中应启用  // 配置请求授权  .authorizeRequests()  .antMatchers("/login", "/register", "/public/**").permitAll() // 这些URL允许匿名访问  .anyRequest().authenticated() // 其他所有请求都需要认证  .and()  // 配置表单登录  .formLogin()  .loginPage("/login") // 自定义登录页面  .defaultSuccessUrl("/home", true) // 登录成功后的默认跳转页面  .failureUrl("/login-error") // 登录失败后的页面  .permitAll() // 允许所有人访问登录页面  .and()  // 配置登出  .logout()  .logoutUrl("/logout") // 登出请求的URL  .logoutSuccessUrl("/login?logout") // 登出成功后的跳转页面  .permitAll() // 允许所有人访问登出功能  .and()  // 添加HTTP安全头部  .headers()  .frameOptions().deny() // 禁止iframe  .and()  // 会话管理  .sessionManagement()  .invalidSessionUrl("/invalid-session"); // 无效会话时的跳转页面  
}3. configure(AuthenticationManagerBuilder auth)
 
此方法用于配置认证管理器(AuthenticationManager),它决定了如何对用户进行身份验证。可以通过它来定义用户信息的来源(如内存、数据库、LDAP等)和密码的加密方式。
@Autowired  
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {  // 使用内存中的用户进行认证  auth  .inMemoryAuthentication()  .withUser("user").password("{noop}password").roles("USER")  .and()  .withUser("admin").password("{noop}admin").roles("USER", "ADMIN");  // 或者使用自定义的用户详情服务  // auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());  
}  @Bean  
public PasswordEncoder passwordEncoder() {  return new BCryptPasswordEncoder();  
}