身份认证与应用安全 / 系统课时

用过滤器校验访问令牌

用过滤器校验访问令牌

JWT 鉴权真正发生在请求进入业务控制器之前。本节使用 OncePerRequestFilter 把令牌提取、验签、用户加载和 SecurityContext 写入串成一次请求流程,并说明无令牌、无效令牌与已认证请求应分别怎样处理。

学习目标

  • 使用 OncePerRequestFilter 实现一次请求中的 JWT 认证处理。
  • 在令牌有效时加载用户并写入 SecurityContextHolder。
  • 正确处理无令牌、无效令牌和已有认证信息三类情况。

过滤器在鉴权链中的位置

JWT 过滤器的职责不是直接决定所有接口能否访问,而是尽早把“这个请求是谁”转换成 Spring Security 能理解的 Authentication。后续授权过滤器再根据接口规则判断是否允许继续访问。

JWT 认证过滤链数据流

OncePerRequestFilter 提供 doFilterInternal 入口,适合把这段逻辑集中在一个过滤器中。关键原则是:没有 Bearer Token 时不要主动制造认证;已有认证时不要重复覆盖;令牌失败时清空上下文并交给统一认证失败入口。

实现 JWT 认证过滤器

下面是片段示例,假设项目已经有 JwtTokenService 负责验签和解析 subject。令牌库可以是任意实现,过滤器只依赖这个应用层接口,因此不会把具体 JWT SDK 细节耦合进 Security 过滤链。

java
package com.example.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenService jwtTokenService;
    private final UserDetailsService userDetailsService;
    private final AuthenticationEntryPoint authenticationEntryPoint;

    public JwtAuthenticationFilter(
            JwtTokenService jwtTokenService,
            UserDetailsService userDetailsService,
            AuthenticationEntryPoint authenticationEntryPoint) {
        this.jwtTokenService = jwtTokenService;
        this.userDetailsService = userDetailsService;
        this.authenticationEntryPoint = authenticationEntryPoint;
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        String token = resolveBearerToken(request);

        if (token != null
                && SecurityContextHolder.getContext().getAuthentication() == null) {
            try {
                String username = jwtTokenService.verifyAndGetSubject(token);
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContext context = SecurityContextHolder.createEmptyContext();
                context.setAuthentication(authentication);
                SecurityContextHolder.setContext(context);
            } catch (InvalidTokenException | UsernameNotFoundException ex) {
                SecurityContextHolder.clearContext();
                authenticationEntryPoint.commence(
                        request,
                        response,
                        new BadCredentialsException("Invalid access token", ex));
                return;
            }
        }

        filterChain.doFilter(request, response);
    }

    private String resolveBearerToken(HttpServletRequest request) {
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7)) {
            return null;
        }

        String token = header.substring(7).trim();
        return token.isEmpty() ? null : token;
    }

    public interface JwtTokenService {
        String verifyAndGetSubject(String token) throws InvalidTokenException;
    }

    public static class InvalidTokenException extends RuntimeException {
        public InvalidTokenException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}

预期结果

令牌缺失时过滤器不写入认证信息并继续执行;令牌有效时,当前请求的 SecurityContextHolder 中会出现带用户权限的 Authentication;验签失败、令牌过期或 subject 对应用户不存在时,过滤器通过 AuthenticationEntryPoint 结束认证流程,典型结果是 HTTP 401。

把过滤器加入 SecurityFilterChain

仅声明 @Component 不代表它一定处在正确的 Security 顺序。需要显式把它加入 SecurityFilterChain,并把会话策略设为无状态,使每次请求都以访问令牌为认证依据。

下面同样是片段示例,/api/auth/login 代表登录接口,实际项目应替换成自己的公开路径。

java
package com.example.config;

import com.example.security.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {

    @Bean
    AuthenticationEntryPoint authenticationEntryPoint() {
        return new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
    }

    @Bean
    SecurityFilterChain securityFilterChain(
            HttpSecurity http,
            JwtAuthenticationFilter jwtAuthenticationFilter,
            AuthenticationEntryPoint authenticationEntryPoint) throws Exception {

        http
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .exceptionHandling(ex -> ex
                        .authenticationEntryPoint(authenticationEntryPoint))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/auth/login").permitAll()
                        .anyRequest().authenticated())
                .addFilterBefore(
                        jwtAuthenticationFilter,
                        UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

预期结果

公开登录接口即使没有 Bearer Token 也可以继续访问;受保护接口没有认证信息时由 Spring Security 拒绝;携带有效令牌时,JWT 过滤器先建立认证,再由后续授权规则决定请求能否进入控制器。

避免过滤器中的三个常见错误

不要把 filterChain.doFilter 放进覆盖整个后续链路的 try 块,否则控制器或后续过滤器抛出的业务异常可能被误判成“JWT 无效”。也不要在令牌已经认证成功后重复加载用户,这既浪费查询,也可能覆盖其他认证机制已经建立的上下文。

一个健壮的 JWT 过滤器只完成认证上下文建立,不把权限判断、业务异常处理和令牌签发混在一起。这样令牌校验失败归认证入口处理,接口权限归授权规则处理,控制器只处理业务。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

用过滤器校验访问令牌

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通