Spring Boot OAuth2 JWT场景下如何在控制器或过滤器中获取Payload
Spring Boot OAuth2 JWT获取Payload实现方案
控制器层获取方式
方式1:@AuthenticationPrincipal 直接注入(推荐)
前提是你已经正确引入spring-boot-starter-oauth2-resource-server依赖,且Security配置类开启了JWT资源服务器支持:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) // 开启OAuth2 JWT资源服务器解析配置 .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); return http.build(); } // 自定义JWT解码器,配置你的签名密钥 @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withSecretKey(Keys.hmacShaKeyFor("你的JWT签名密钥".getBytes(StandardCharsets.UTF_8))).build(); } }
控制器直接注入Jwt对象即可获取所有Payload字段:
@GetMapping("/user") public String getUserInfo(@AuthenticationPrincipal Jwt jwt) { // 获取单个指定字段 String timeCreated = jwt.getClaim("time_created"); // 获取全部Payload键值对 Map<String, Object> allPayload = jwt.getClaims(); System.out.println(timeCreated); return "success"; }
方式2:从SecurityContext中获取
@GetMapping("/user") public String getUserInfo() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth.getPrincipal() instanceof Jwt jwt) { String timeCreated = jwt.getClaim("time_created"); System.out.println(timeCreated); } return "success"; }
过滤器层获取方式
过滤器需要配置执行顺序在Spring Security的JWT认证过滤器之后,避免未完成认证就获取principal:
@Component // 优先级低于内置的BearerTokenAuthenticationFilter,保证先完成认证再执行 @Order(Ordered.HIGHEST_PRECEDENCE + 10) public class JwtParseFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getPrincipal() instanceof Jwt jwt) { String timeCreated = jwt.getClaim("time_created"); // 可以将字段存入request传递给后续逻辑 request.setAttribute("time_created", timeCreated); } filterChain.doFilter(request, response); } }
常见不生效排查点
- 接口路径不要配置在
permitAll免鉴权规则中,免鉴权接口不会触发JWT解析逻辑 - 请求头
Authorization必须符合Bearer {token}格式,不要遗漏Bearer前缀 - JWT签名密钥配置和签发端保持一致,避免解析失败导致principal为null
内容的提问来源于stack exchange,提问作者mateo cunha
相关产品推荐
相关产品推荐

