当前位置:首页 > 文章列表 > 文章 > java教程 > SpringSecurity配置JWT过滤器详解

SpringSecurity配置JWT过滤器详解

2025-07-18 23:09:26 0浏览 收藏

文章不知道大家是否熟悉?今天我将给大家介绍《Spring Security配置JWT过滤器方法》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

Spring Security:为特定URL模式配置JWT过滤器

本教程详细讲解如何在Spring Boot Security中,精确控制JWT(JSON Web Token)过滤器的应用范围,使其仅作用于指定的URL模式,而非全局生效。通过继承AbstractAuthenticationProcessingFilter并结合RequestMatcher接口,开发者可以灵活定义哪些请求路径需要JWT认证,从而优化安全策略,避免不必要的性能开销,并增强应用的模块化安全性。文章将提供详细的代码示例和配置步骤,帮助读者实现定制化的安全过滤逻辑。

在Spring Security中,我们经常需要自定义过滤器来处理特定的认证或授权逻辑,例如JWT认证。然而,默认情况下,通过HttpSecurity.addFilterBefore()或addFilterAt()添加的过滤器会作用于所有进来的HTTP请求。对于JWT认证而言,通常我们只希望它对受保护的API路径(例如/api/**)生效,而对静态资源、登录页面或公共接口则无需进行JWT验证。本文将介绍如何利用Spring Security提供的AbstractAuthenticationProcessingFilter和RequestMatcher接口,实现JWT过滤器的精确控制。

挑战:全局过滤器与局部需求

当我们将一个自定义JWT过滤器(例如CustomJwtAuthenticationFilter)通过以下方式添加到安全链中时:

http.addFilterBefore(customJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

这个customJwtAuthenticationFilter将会在UsernamePasswordAuthenticationFilter之前,对所有进入应用的请求进行处理。这意味着即使是访问/login、/或任何非API路径,该过滤器也会被触发,这不仅可能导致不必要的性能开销,还可能在某些情况下抛出异常(例如,尝试从没有JWT的请求头中解析令牌)。

解决方案:AbstractAuthenticationProcessingFilter与RequestMatcher

Spring Security提供了一个抽象类AbstractAuthenticationProcessingFilter,它专门用于处理基于请求匹配的认证流程。这个类的核心在于其构造函数可以接收一个RequestMatcher对象。当一个请求到达时,AbstractAuthenticationProcessingFilter会首先调用其内部的RequestMatcher的matches()方法。只有当matches()方法返回true时,过滤器才会继续执行其认证逻辑(即调用attemptAuthentication()方法);否则,它会直接跳过认证过程,将请求传递给安全链中的下一个过滤器。

RequestMatcher是一个接口,它定义了如何根据HttpServletRequest来判断一个请求是否匹配特定条件。Spring Security提供了多种RequestMatcher的实现,其中最常用的是:

  • AntPathRequestMatcher:基于Ant风格路径模式匹配URL。
  • OrRequestMatcher:将多个RequestMatcher组合,只要有一个匹配就返回true。
  • AndRequestMatcher:将多个RequestMatcher组合,只有所有都匹配才返回true。
  • NegatedRequestMatcher:对另一个RequestMatcher的结果取反。

实现步骤

我们将通过以下步骤实现JWT过滤器的精确控制:

1. 改造 CustomJwtAuthenticationFilter

让你的JWT认证过滤器继承AbstractAuthenticationProcessingFilter,并在构造函数中接收RequestMatcher和AuthenticationManager。

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义JWT认证过滤器,仅对匹配特定RequestMatcher的请求进行处理。
 */
public class CustomJwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * 构造函数。
     * @param requiresAuthenticationRequestMatcher 定义哪些请求需要此过滤器处理的RequestMatcher
     * @param authenticationManager 认证管理器,用于执行认证逻辑
     */
    public CustomJwtAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher, AuthenticationManager authenticationManager) {
        super(requiresAuthenticationRequestMatcher); // 将RequestMatcher传递给父类
        setAuthenticationManager(authenticationManager); // 设置认证管理器
    }

    /**
     * 实现JWT认证的核心逻辑。
     * 只有当RequestMatcher匹配时,此方法才会被调用。
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        // 在这里实现你的JWT解析和认证逻辑
        // 例如:从请求头中获取JWT令牌
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            // 如果没有Bearer Token,抛出认证异常,或返回null让后续认证机制处理
            throw new AuthenticationException("Missing or invalid JWT token in Authorization header") {};
        }

        String jwtToken = authorizationHeader.substring(7); // 提取JWT字符串

        // TODO: 根据你的JWT库和业务逻辑验证jwtToken,并构建一个Authentication对象
        // 例如:
        // JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(jwtToken);
        // return getAuthenticationManager().authenticate(authenticationToken); // 委托给AuthenticationManager进行认证

        // 示例:此处仅为演示,实际应替换为你的JWT验证逻辑
        System.out.println("Processing JWT for path: " + request.getRequestURI());
        // 假设成功验证并返回一个Authentication对象
        // return new UsernamePasswordAuthenticationToken("user", null, Collections.emptyList());
        throw new UnsupportedOperationException("JWT认证逻辑待实现,请替换为实际的令牌验证和用户身份构建。");
    }

    // 可选:重写successfulAuthentication和unsuccessfulAuthentication方法来处理认证成功或失败后的逻辑
    // @Override
    // protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
    //     super.successfulAuthentication(request, response, chain, authResult);
    //     // 认证成功后继续过滤器链
    //     chain.doFilter(request, response);
    // }

    // @Override
    // protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
    //     // 认证失败处理,例如返回401 Unauthorized
    //     response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    //     response.getWriter().write("Authentication Failed: " + failed.getMessage());
    // }
}

2. 定义 RequestMatcher

针对“只过滤/api/**路径”的需求,我们可以使用AntPathRequestMatcher。

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

// 简单匹配单个路径模式
// RequestMatcher apiRequestMatcher = new AntPathRequestMatcher("/api/**");

// 如果需要匹配多个路径模式,可以使用OrRequestMatcher
// RequestMatcher multiPathMatcher = new OrRequestMatcher(
//     new AntPathRequestMatcher("/api/v1/**"),
//     new AntPathRequestMatcher("/secure/**")
// );

3. 配置 Spring Security

在你的安全配置类(通常是继承WebSecurityConfigurerAdapter或使用SecurityFilterChain)中,将改造后的CustomJwtAuthenticationFilter作为Bean注入,并添加到安全链中。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 假设你有一个JwtAuthenticationEntryPoint处理认证失败的入口点
    // @Autowired
    // private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    // 假设你有一个UserDetailsService用于加载用户详情(如果JWT认证需要)
    // @Autowired
    // private UserDetailsService userDetailsService;

    /**
     * 配置HTTP安全策略。
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // 禁用CSRF,因为JWT是无状态的
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 设置会话管理为无状态
            .and()
            // .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and() // 配置认证入口点处理未认证请求
            .authorizeRequests()
            .antMatchers("/api/**").authenticated() // 明确指定 /api/** 路径需要认证
            .anyRequest().permitAll() // 其他所有请求都允许访问
            .and()
            // 将我们定制的JWT过滤器添加到UsernamePasswordAuthenticationFilter之前
            .addFilterBefore(customJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 将CustomJwtAuthenticationFilter注册为Spring Bean。
     * 注意:这里需要捕获AuthenticationManagerBean()抛出的异常。

终于介绍完啦!小伙伴们,这篇关于《SpringSecurity配置JWT过滤器详解》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

即梦AI积分兑换教程全流程详解指南即梦AI积分兑换教程全流程详解指南
上一篇
即梦AI积分兑换教程全流程详解指南
GolangRPC客户端:连接池与超时控制详解
下一篇
GolangRPC客户端:连接池与超时控制详解
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    511次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    498次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • AI代码助手:Amazon CodeWhisperer,高效安全的代码生成工具
    CodeWhisperer
    Amazon CodeWhisperer,一款AI代码生成工具,助您高效编写代码。支持多种语言和IDE,提供智能代码建议、安全扫描,加速开发流程。
    11次使用
  • 畅图AI:AI原生智能图表工具 | 零门槛生成与高效团队协作
    畅图AI
    探索畅图AI:领先的AI原生图表工具,告别绘图门槛。AI智能生成思维导图、流程图等多种图表,支持多模态解析、智能转换与高效团队协作。免费试用,提升效率!
    36次使用
  • TextIn智能文字识别:高效文档处理,助力企业数字化转型
    TextIn智能文字识别平台
    TextIn智能文字识别平台,提供OCR、文档解析及NLP技术,实现文档采集、分类、信息抽取及智能审核全流程自动化。降低90%人工审核成本,提升企业效率。
    44次使用
  • SEO  简篇 AI 排版:3 秒生成精美文章,告别排版烦恼
    简篇AI排版
    SEO 简篇 AI 排版,一款强大的 AI 图文排版工具,3 秒生成专业文章。智能排版、AI 对话优化,支持工作汇报、家校通知等数百场景。会员畅享海量素材、专属客服,多格式导出,一键分享。
    40次使用
  • SEO  小墨鹰 AI 快排:公众号图文排版神器,30 秒搞定精美排版
    小墨鹰AI快排
    SEO 小墨鹰 AI 快排,新媒体运营必备!30 秒自动完成公众号图文排版,更有 AI 写作助手、图片去水印等功能。海量素材模板,一键秒刷,提升运营效率!
    38次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码