暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Spring Security5.6升级到5.7+

原创 我为啥没洁癖 2023-12-12
505

Spring Security5.6升级到5.7+

Spring Boot 2.7.0 版本之前,需要写个配置类继承 WebSecurityConfigurerAdapter,然后重写 Adapter 中方法进行配置;

Spring Boot 2.7.0 版本之后无需再继承 WebSecurityConfigurerAdapter,只需直接声明配置类,再配置一个生成 SecurityFilterChainBean 方法,把原来 HttpSecurity 配置移动到该方法中即可。

Security整合配置调整

SecurityConfig配置方式变更,其他类都不需要改动,功能完全一样。

  1. 将原来的configure(HttpSecurity httpSecurity)方法中的配置全部移动到filterChain(HttpSecurity http)中、额外加上return http.build();
  2. 注入AuthenticationConfiguration对象,实例化AuthenticationManager,自定义filter中的AuthenticationManager通过此处实例化的AuthenticationManager获得。
@EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled=true) public class SecurityConfig { // 验证失败处理类 @Autowired private AuthenticationEntryPointImpl authenticationEntryPoint; @Autowired private AuthenticationConfiguration authenticationConfiguration; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http // 跨域处理 .csrf().disable() .headers().frameOptions().disable().and() // 基于token关闭session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() // 认证失败处理类 .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint) // .accessDeniedHandler(accessDeniedHandler) .and() // 请求白名单 .authorizeRequests() .antMatchers( HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js" ).permitAll() // 出白名单外其他的都要验证 .anyRequest().authenticated().and() .addFilter(new TokenLoginFilter(authenticationManager())) .addFilterBefore(new TokenVerifyFilter(authenticationManager()), TokenLoginFilter.class); return http.build(); } // 验证对象管理器实例化 @Bean public AuthenticationManager authenticationManager() throws Exception { return authenticationConfiguration.getAuthenticationManager(); } // 密码校验器 @Bean public PasswordEncoder passwordEncoder(){ return new MyPasswordEncode(); } }
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论