Java 后端 / 系统课时

签发与校验 JWT

签发与校验 JWT

本课实现一条完整的 JWT 无状态认证链路:账号密码登录后签发访问令牌,后续请求自动校验签名、签发方与过期时间,并把令牌中的主体和权限恢复到 SecurityContext。

学习目标

  • 设计访问令牌中必须保留的声明与有效期
  • 使用 Spring Security 的 JwtEncoder 和 JwtDecoder 完成签发与校验
  • 让资源服务器自动恢复认证上下文并处理过期令牌

设计访问令牌

访问令牌至少需要 sub、iat、exp 和 iss。sub 表示用户身份,iat 与 exp 限定令牌生命周期,iss 用于阻止其他系统签发的令牌被误接收。权限可放在 scope 中,但不要把密码、手机号等敏感信息写入令牌,因为 JWT 的载荷默认只编码、不加密。

JWT 签发校验与上下文恢复时序图

Spring Security 资源服务器会在每个请求中读取 Authorization: Bearer <TOKEN>,调用 JwtDecoder 校验令牌,并在成功后创建 JwtAuthenticationToken。因此不需要自行编写过滤器或手动操作 SecurityContextHolder。

添加 JWT 依赖

在已有 Web 与 Security 依赖的 Spring Boot 3 项目中加入资源服务器模块。它同时提供 JWT 编解码与 Bearer Token 过滤链。

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

生效后,项目可以使用 JwtEncoder、JwtDecoder 和 oauth2ResourceServer 配置。依赖配置本身不会产生控制台业务输出,可通过后面的启动与接口请求验证。

完成签发与校验

下面的单文件示例使用 HS256。密钥从环境变量读取,解码后至少为 32 字节;生产环境应由密钥管理系统注入,并制定轮换策略。

java
package com.example.jwt;

import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import java.util.stream.Collectors;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.nimbusds.jose.jwk.source.ImmutableSecret;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class JwtApplication {
    private static final String ISSUER = "anystack-api";
    private static final Duration ACCESS_TOKEN_TTL = Duration.ofMinutes(15);

    public static void main(String[] args) {
        SpringApplication.run(JwtApplication.class, args);
    }

    @Bean
    SecretKey jwtSecret(@Value("${JWT_SECRET_BASE64}") String secretBase64) {
        byte[] keyBytes = Base64.getDecoder().decode(secretBase64);
        if (keyBytes.length < 32) {
            throw new IllegalArgumentException("JWT 密钥至少需要 32 字节");
        }
        return new SecretKeySpec(keyBytes, "HmacSHA256");
    }

    @Bean
    JwtEncoder jwtEncoder(SecretKey secretKey) {
        return new NimbusJwtEncoder(new ImmutableSecret<>(secretKey));
    }

    @Bean
    JwtDecoder jwtDecoder(SecretKey secretKey) {
        NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey)
                .macAlgorithm(MacAlgorithm.HS256)
                .build();
        decoder.setJwtValidator(JwtValidators.createDefaultWithIssuer(ISSUER));
        return decoder;
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    UserDetailsService userDetailsService(PasswordEncoder encoder) {
        var alice = User.withUsername("alice")
                .password(encoder.encode("S3curePass!"))
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(alice);
    }

    @Bean
    AuthenticationManager authenticationManager(
            AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/auth/login").permitAll()
                        .requestMatchers("/api/me").authenticated()
                        .anyRequest().denyAll())
                .oauth2ResourceServer(resourceServer -> resourceServer
                        .jwt(Customizer.withDefaults()));
        return http.build();
    }

    @RestController
    @RequestMapping("/api")
    static class ApiController {
        private final AuthenticationManager authenticationManager;
        private final JwtEncoder jwtEncoder;

        ApiController(AuthenticationManager authenticationManager,
                      JwtEncoder jwtEncoder) {
            this.authenticationManager = authenticationManager;
            this.jwtEncoder = jwtEncoder;
        }

        @PostMapping("/auth/login")
        ResponseEntity<?> login(@RequestBody LoginRequest request) {
            try {
                Authentication authentication = authenticationManager.authenticate(
                        new UsernamePasswordAuthenticationToken(
                                request.username(), request.password()));

                Instant now = Instant.now();
                String scope = authentication.getAuthorities().stream()
                        .map(GrantedAuthority::getAuthority)
                        .map(value -> value.replaceFirst("^ROLE_", "").toLowerCase())
                        .collect(Collectors.joining(" "));

                JwtClaimsSet claims = JwtClaimsSet.builder()
                        .issuer(ISSUER)
                        .issuedAt(now)
                        .expiresAt(now.plus(ACCESS_TOKEN_TTL))
                        .subject(authentication.getName())
                        .claim("scope", scope)
                        .build();

                JwsHeader header = JwsHeader.with(MacAlgorithm.HS256)
                        .type("JWT")
                        .build();

                String accessToken = jwtEncoder.encode(
                        JwtEncoderParameters.from(header, claims))
                        .getTokenValue();

                return ResponseEntity.ok(new TokenResponse(
                        accessToken, "Bearer", ACCESS_TOKEN_TTL.toSeconds()));
            } catch (AuthenticationException ex) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(Map.of("code", "INVALID_CREDENTIALS"));
            }
        }

        @GetMapping("/me")
        MeResponse me(Authentication authentication) {
            var authorities = authentication.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .toList();
            return new MeResponse(authentication.getName(), authorities);
        }
    }

    record LoginRequest(String username, String password) {
    }

    record TokenResponse(String accessToken, String tokenType, long expiresIn) {
    }

    record MeResponse(String username, java.util.List<String> authorities) {
    }
}

这里的默认权限转换器会把 scope 中的 user 转为 SCOPE_user。若业务使用 ROLE_ADMIN 之类的角色声明,应增加自定义 JwtAuthenticationConverter,不要在控制器中临时解析字符串。

启动并验证

先设置演示密钥并启动项目。示例密钥仅用于本地学习,实际值必须替换。

bash
export JWT_SECRET_BASE64='MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY='
mvn spring-boot:run

预期输出

text
Started JwtApplication in <TIME> seconds

应用启动后,先登录取得令牌,再用令牌访问受保护接口。

bash
PORT=8080
TOKEN=$(curl -s -X POST "http://localhost:$PORT/api/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"alice","password":"S3curePass!"}' \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["accessToken"])')

curl -s "http://localhost:$PORT/api/me" \
  -H "Authorization: Bearer $TOKEN"

预期输出

json
{"username":"alice","authorities":["SCOPE_user"]}

超过 15 分钟后再次使用同一令牌,或修改令牌任意字符,资源服务器都会返回 401 Unauthorized。时间校验由 JwtTimestampValidator 随默认校验器执行,签发方则由 createDefaultWithIssuer 校验。

生产边界

访问令牌应保持短有效期,并始终通过 HTTPS 传输。JWT 一旦签发通常不能主动撤回;需要退出登录、设备踢下线或高风险操作即时失效时,应配合刷新令牌、令牌版本号或撤销列表。

对外服务更适合使用非对称算法,让认证服务持有私钥、资源服务只持有公钥。无论采用哪种算法,都必须固定允许的算法,不能信任令牌头部自行声明的算法。

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

目录与阅读设置

阅读设置

17

记录一个想法

签发与校验 JWT

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

登录哪都通