SpringSecurity安全框架

前述

随着 Spring Boot 2.7.0 的发布,Spring Security 同样也升级到了 5.7.1,升级之后,原有的WebSecurityConfigurerAdapter 方法正式被弃用了,但是主要玩法变化不大

  • 后续笔记将以 5.7.x 以上版本进行记录

HttpSecurity新旧对比

旧版本

@Configuration
static class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/**")
            .authorizeRequests(authorize -> authorize
            .anyRequest().authenticated()
            );
    }
}

新版本

@Configuration
public class SecurityConfiguration {

   @Bean
   SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
            .antMatcher("/**")
            .authorizeRequests(authorize -> authorize
            .anyRequest().authenticated()
            )
            .build();
     }
}

WebSecurity新旧对比

旧版本

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        // 仅仅作为演示
        // 如果你需要忽略URL,应该通过HttpSecurity.authorizeHttpRequests的permitAll来实现。
        web.ignoring().antMatchers("/ignore1", "/ignore2");
    }

}

新版本

@Configuration
public class SecurityConfiguration {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        // 仅仅作为演示
        return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
    }

}

AuthenticationManager新旧对比

旧版本

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    // 本地配置
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication();
    }
    
    // 开启全局配置需要覆写其authenticationManagerBean()方法并标记为Bean
  	@Bean(name name="myAuthenticationManager")
  	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
	       return super.authenticationManagerBean();
	}
}

新版本

@Configuration
public class SecurityConfiguration {

    // 本地配置通过HttpSecurity.authenticationManager实现
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
            .anyRequest().authenticated())
            .httpBasic(withDefaults())
            .authenticationManager(new CustomAuthenticationManager());
    }

}
// 全局配置摆脱了依赖WebSecurityConfigurerAdapter.authenticationManagerBean()方法,只需要定义一个AuthenticationManager类型的Bean即可    
@Bean
AuthenticationManager ldapAuthenticationManager(BaseLdapPathContextSource contextSource) {
    LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);
    factory.setUserDnPatterns("uid={0},ou=people");
    factory.setUserDetailsContextMapper(new PersonContextMapper());
    return factory.createAuthenticationManager();
}
Last Updated 2024/5/24 16:21:58