认证鉴权框架SpringSecurity-6--6.x版本升级篇

1、Springboot和springSecurity版本关系

前面少介绍了一个概念,springSecurity是spring家族的一员,springboot同样也是spring家族的一员。我们在pom中引入使用springboot时,需要指定springboot的版本。在引入springSecurity时,则不需要指定版本,spring会默认添加最匹配的版本。

版本主要关系如下:
Springboot2.X版本–对应springSecurity5.X版本
Springboot3.X版本–对应springSecurity6.X版本

2、5.X版本和6.X版本的区别

Spring Security 6.x 引入了一些重要的变化和改进,与之前的版本(如 Spring Security 5)相比有一些区别。最主要的区别就是弃用了WebSecurityConfigurerAdapter 类,使用了更加组件式的配置。简单来说就是直接定义一个或多个 SecurityFilterChain通过 bean方式注入spring容器中就达到了配置安全规则的结果。

3、升级改造流程

(1)、引入springboot3.X版本依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>my-security-app</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>

    <dependencies>
        <!-- Spring Boot Starter Security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

(2)、老版5.x版本的配置升级

1、老版本5.x配置类示例
import com.demo.exception.CustomAuthenticationFailureHandler;
import com.demo.exception.Http401AuthenticationEntryPoint;
import com.demo.filter.JWTAuthenticationFilter;
import com.demo.filter.JWTLoginFilter;
import com.demo.service.CustomAuthenticationProvider;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity的配置
 * 通过SpringSecurity的配置,将JWTLoginFilter,JWTAuthenticationFilter组合在一起
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**白名单*/
    private static final String[] AUTH_WHITELIST = {
            "/v2/api-docs",
            "/swagger-resources/**",
            "/test/**"
    };

    @Autowired
    private UserService userService;
    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    // 设置 HTTP 验证规则
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .anyRequest().authenticated() 
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(
                        new Http401AuthenticationEntryPoint())
                .and()
                .addFilterBefore(new JWTLoginFilter(authenticationManager(),customAuthenticationFailureHandler,userService), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new JWTAuthenticationFilter(authenticationManager(),userService), UsernamePasswordAuthenticationFilter.class);        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    }
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自定义认证提供者
        auth.authenticationProvider(new CustomAuthenticationProvider(userService));
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 白名单接口放行
        web.ignoring().antMatchers(AUTH_WHITELIST);
    }
}
2、新版本6.x配置类示例

注意看的地方

import com.demo.exception.CustomAuthenticationFailureHandler;
import com.demo.exception.Http401AuthenticationEntryPoint;
import com.demo.filter.JWTAuthenticationFilter;
import com.demo.filter.JWTLoginFilter;
import com.demo.service.CustomAuthenticationProvider;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity的配置
 * 通过SpringSecurity的配置,将JWTLoginFilter,JWTAuthenticationFilter组合在一起
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
public class WebSecurityConfig {

    /**白名单
     */
    private static final String[] AUTH_WHITELIST = {
            "/v2/api-docs",
            "/swagger-resources",
            "/test/**"
    };

    @Autowired
    private UserService userService;

    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Bean    构建过滤器链返回
    protected SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(
                        new Http401AuthenticationEntryPoint())
                .and()
                .addFilterBefore(new JWTLoginFilter(authenticationManager(),customAuthenticationFailureHandler,userService), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new JWTAuthenticationFilter(authenticationManager(),userService), UsernamePasswordAuthenticationFilter.class);
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
		
		httpSecurity.authenticationProvider(new CustomAuthenticationProvider(userService))   使用自定义认证提供者,直接封装到httpSecurity中	
		
		return http.build();     构建过滤链并返回
    }

   @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
         白名单接口放行
		return (web) -> web.ignoring().antMatchers(AUTH_WHITELIST);
    }
}

(3)、升级总结

1、6.X的配置类不在继承WebSecurityConfigurerAdapter抽象类
2、HttpSecurity配置后,需要调用.build方法生成过滤器链返回,注入到容器中。
3、自定义的UserDetailService不需要AuthenticationManagerBuilder指定,直接注入spring容器就行。
4、自定义AuthenticationProvider认证方式,通过HttpSecurity配置,添加到过滤器链中。
5、白名单返回WebSecurityCustomizer 对象。

### Spring Security 失败解决方案及原因分析 #### 一、失败常见表现形式及其影响 当应用程序中的用户尝试访问受保护资源而未通过授验证时,即发生失败。这通常表现为HTTP状态码`403 Forbidden`返回给客户端[^1]。 #### 二、可能的原因 1. **限设置不当** 如果角色或限配置错误,则即使合法用户也可能被拒绝访问某些页面或操作。例如,在基于方法的安全性声明中指定的角色名称拼写有误,或者在URL匹配规则里遗漏了必要的路径模式[^2]。 2. **会话超时/令牌失效** 用户登录后的凭证(如JWT token)过期后如果没有及时刷新,再次发起请求就会触发失败机制。这种情况尤其容易发生在长时间闲置后再活动的情况下[^3]。 3. **自定义过滤器逻辑缺陷** 开发者可能会扩展默认行为来适应特定业务场景的需求,比如创建额外的身份验证层或是修改原有流程。然而如果这些改动存在漏洞,那么即便其他部分工作正常也难以避免出现问题[^4]。 #### 三、排查步骤与修复建议 - **审查安全策略文件**:仔细核对application.yml 或 application.properties 中有关security的属性设定;确保所有涉及限控制的地方都遵循一致的标准并正确无误地指定了所需条件。 - **启用调试日志输出**:调整logback.xml或其他日志框架配置以增加关于spring security的日志级别至DEBUG甚至TRACE级,以便更清晰地观察整个过程中的每一步骤以及任何潜在异常情况的发生位置和具体信息。 - **模拟真实环境下的测试案例**:构建尽可能贴近实际使用的单元测试用例集,特别是针对边界状况进行充分覆盖,以此检验现有措施的有效性和稳定性的同时也能帮助定位隐藏较深的问题所在之处。 - **检查第三方组件兼容性**:对于引入外部库的情况要特别留意版本间的差异可能导致的行为变化,必要时查阅官方文档确认是否存在已知冲突点,并考虑升级到最新稳定版解决问题。 ```java // 示例代码展示如何捕获并处理失败事件 @Override protected void configure(HttpSecurity http) throws Exception { http.exceptionHandling() .authenticationEntryPoint(new Http403ForbiddenEntryPoint()) .accessDeniedHandler((request, response, accessDeniedException) -> { // 自定义处理逻辑... System.out.println("Access Denied!"); }); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值