当前位置: 首页 > 图灵资讯 > 技术篇> Spring Security:为特定URL模式配置JWT过滤器

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

来源:图灵教育
时间:2025-07-08 19:31:39

Spring Security:JWT过滤器配备了特定的URL模式

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

spring 在security中,我们通常需要自定义过滤器来处理特定的认证或授权逻辑,例如jwt认证。但是,默认情况下,通过httpsecurity.addfilterbefore()或addfilterat()添加的过滤器将作用于所有进入的http请求。对于jwt认证,我们通常只希望它对受保护的api路径(如/api/**)生效,无需jwt验证静态资源、登录页面或公共界面。本文将介绍如何使用spring。 security提供的abstractauthenticationprocessingfilter和requestmatcher接口,实现jwt过滤器的精确控制。

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

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

http.addFilterBefore(customJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

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

AbstractauthenticationProcesingFilter和RequestMatcher

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

Requestmatcher是一个界面,它定义了如何根据Httpservletrequest来判断一个请求是否符合特定条件。Spring Security提供了各种Requestmatcher的实现,其中最常用的是:

  • AntPathRequestMatcher:URL与Ant风格路径模式相匹配。
  • OrRequestMatcher:将多个RequestMatcher组合起来,只要有一个匹配,就返回true。
  • AndRequestMatcher:将多个RequestMatcher组合起来,只有全部匹配才能返回true。
  • NegatedRequestMatcher:取反另一个RequestMatcher的结果。
实现步骤

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

1. 改造 CustomJwtAuthenticationFilter

让您的JWT认证过滤器继承AbstractauthenticationProcessingfilter,并在构造函数中接收Requestmatcher和Authenticationmananager。

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: jwttoken根据您的JWT库和业务逻辑进行验证,构建Authentication对象
        // 例如:
        // JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(jwtToken);
        // return getAuthenticationManager().authenticate(authenticationToken); // 委托Authenticationmanger进行认证

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

    // 可选:重写sucesfulauthentication和unsucesfulauthentication方法,以处理认证成功或失败后的逻辑
    // @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)中,将改造后的CustomJwtautinticationfilter注入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过滤器添加到UsernamePaswordauthenticationfilter之前
            .addFilterBefore(customJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * CustomJwtauthentionfilter注册为Spring Bean。
     * 注:这里需要捕获AuthenticationMangerBean()抛出的异常。

以上是Spring Security:为特定URL模式配置JWT过滤器的详细信息,请关注图灵教育的其他相关文章!