用的挺顺手的 Spring Security 配置类,居然就要被官方弃用了

用过 WebSecurityConfigurerAdapter 的都知道对 Spring Security 十分重要,总管 Spring Security 的配置体系。但是马上这个类要废了,你没有看错,这个类将在5.7版本被 @Deprecated 所标记了,未来这个类将被移除。

相关的issues已经被处理并关闭

对此对此网友大呼“学着学着就被弃用了”。既然马上要弃用了,总要有个过渡方案或者新玩法吧。

早在2021年3月份胖哥就写了一篇文章,把新玩法给明明白白说清楚了,如果你看了的话,肯定不会学废弃技术。这里把整套的替代方案再搞一遍,可别再学过时技术了。

版本需要 Spring Security 5.4.x 及以上。

HttpSecurity新旧玩法对比

旧玩法:

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

新玩法:

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

相关原理去看这一篇文章。

WebSecurity新旧玩法对比

使用 WebSecurity.ignoring() 忽略某些URL请求,这些请求将被 Spring Security 忽略,这意味着这些URL将有受到 CSRF、XSS、Clickjacking 等攻击的可能。以下示例仅仅作为演示,请勿使用在生产环境。是不是又学到了呢?

旧玩法:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        // 仅仅作为演示
        web.ignoring().antMatchers("/ignore1", "/ignore2");
    }

}

新玩法:

@Configuration
public class SecurityConfiguration {

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

}

如果你需要忽略URL,请考虑通过 HttpSecurity.authorizeHttpRequests 的 permitAll 来实现。

AuthenticationManager新旧玩法对比

AuthenticationManager 配置主要分为全局的(Global )、本地的(Local)。

旧玩法

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication();
    }
}

上面是通过 WebSecurityConfigurerAdapter 开启的是本地配置。开启全局配置需要覆写其 authenticationManagerBean() 方法并标记为Bean:

       @Bean(name name="myAuthenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

新玩法

本地配置通过 HttpSecurity.authenticationManager 实现:

@Configuration
public class SecurityConfiguration {

    @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();
    }

当然还可以通过自定义 GlobalAuthenticationConfigurerAdapter 并注入 Spring IoC 来修改 AuthenticationManagerBuilder ,不限制数量,但是要注意有排序问题。相关的思维导图:

最后

很多技术方案都不是直接更改的,是会有一个变化的过程,只要你紧追变化,其实也就没有变化。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
AuthenticationManagerSpring Security的核心接口之一,它是一个认证管理器,用于处理身份验证请求。在配置AuthenticationManager时,需要指定一个或多个AuthenticationProvider,它们将负责实际的身份验证工作。以下是配置AuthenticationManager的步骤: 1.创建一个实现了UserDetailsService接口的。 2.在Spring Security配置中,使用AuthenticationManagerBuilder定义一个AuthenticationManager的实例。 3.在AuthenticationManagerBuilder中,使用userDetailsService()方法将步骤1中创建的UserDetailsService实例传递给AuthenticationManagerBuilder。 4.添加一个AuthenticationProvider实例,它将使用步骤1中创建的UserDetailsService实例进行身份验证。 5.在WebSecurityConfigurerAdapter中重写configure(AuthenticationManagerBuilder auth)方法,将AuthenticationManagerBuilder实例传递给该方法。 6.在configure(HttpSecurity http)方法中,使用authenticationManager()方法返回的AuthenticationManager实例,配置身份验证规则和访问控制规则。 以下是一个示例代码片段,演示了如何配置AuthenticationManager: @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); auth.authenticationProvider(authenticationProvider()); } private AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userDetailsService); provider.setPasswordEncoder(passwordEncoder()); return provider; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("USER", "ADMIN") .antMatchers("/login/**").permitAll() .and() .formLogin() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/login?logout") .and() .exceptionHandling() .accessDeniedPage("/access-denied"); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值