Spring Security升级到5.7.x

Spring Security升级到5.7.x

问题描述

WebSecurityConfigurerAdapter类是Spring Security中经常使用到的一个类,用于快速配置WebSecurity。在升级到5.7版本后这个类被废弃掉了,因此其提供的一些API无法使用。在这里提供升级Spring Security后需要做的事情。

解决方案

原有的配置类:

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); // 省略其他的HttpSecurity配置
    }

		@Override
		public void configure(WebSecurity web) throws Exception {
				web.ignoring().antMatchers("/url");
		}
}

原有的配置类取消继承WebSecurityConfigurerAdapter

@Configuration
public class SpringSecurityConfig {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); // 省略其他的HttpSecurity配置
    }

		@Override
		public void configure(WebSecurity web) throws Exception {
				web.ignoring().antMatchers("/url");
		}
}

重新配置HttPSecurity和WebSecurity

在完成上一步之后,可能会在运行时产生找不到HttpSecurity类型的Bean的异常,因此需要在原有的配置类上加上@EnableWebSecurity注解,同时修改原有的配置方法。代码如下:

@Configuration
@EnableWebSecurity  // 如果有找不到HttpSecurity类型Bean的异常,就添加这个注解
public class SpringSecurityConfig {
    @Bean
		public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
				http.csrf().disable();
				return http.build();
		}

		@Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/url");
    }
}

配置AuthenticationManager(关键步骤)

在完成上面的步骤之后,仍然会有可能出现找不到AuthenticationManager类型Bean的错误,这时需要将这个Bean暴露出来,代码如下:

@Configuration
@EnableWebSecurity  // 如果有找不到HttpSecurity类型Bean的异常,就添加这个注解
public class SpringSecurityConfig {
    @Bean
		public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
				http.csrf().disable();
				return http.build();
		}

		@Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/url");
    }

		@Bean
		public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }
}

这时代码能够成功运行,不再产生报错。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OriginCoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值