栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Security升级到5.7.x

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1025104.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号