如何验证 JWT 中的自定义声明 org_id?
解读
在国内 Spring 技术栈面试中,JWT 验证是“安全+微服务”高频考点。
面试官抛出“自定义声明 org_id”这一限定,意在考察三点:
- 你是否真正动手解析过 JWT 负载,而非只会调用
getClaim(); - 你是否理解业务级声明与标准声明的区分,并能在网关或业务层做细粒度授权;
- 你是否掌握 Spring Security 5.x 的可扩展认证架构(
JwtAuthenticationProvider→JwtAuthenticationToken→AuthorizationManager),而不是把验证逻辑写在 Controller 里。
回答时务必体现“解析→校验→授权”三步闭环,并给出可落地的 Spring 配置代码片段。
知识点
- JWT 结构:Header.Payload.Signature,Payload 中的自定义声明属于公有声明或私有声明,需按业务约定命名。
- Nimbus JwtDecoder:Spring Security 默认使用
NimbusJwtDecoder,支持JWK Set URL或对称密钥解析,返回Jwt对象。 - JwtAuthenticationToken:Spring Security 将解析后的
Jwt封装成JwtAuthenticationToken,其getTokenAttributes()可取出org_id。 - AuthorizationManager:Spring Security 5.8+ 推荐用
AuthorizationManager<RequestAuthorizationContext>取代已废弃的AccessDecisionVoter,实现动态权限决策。 - 异常翻译:国内项目通常要求错误码标准化,需把
BadJwtException、JwtExpiredException翻译为自定义AuthException,并返回统一 JSON。
答案
步骤一:定义业务规则
org_id 为字符串类型,长度 8~16,只允许数字与字母;网关层必须与请求头 X-Org-Id 做一致性校验(防横向越权)。
步骤二:自定义 JwtAuthenticationProvider
@Component
public class OrgIdJwtAuthenticationProvider implements AuthenticationProvider {
private final JwtDecoder jwtDecoder;
public OrgIdJwtAuthenticationProvider(JwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication;
Jwt jwt = jwtDecoder.decode(bearer.getToken());
// 1. 解析自定义声明
String orgId = jwt.getClaimAsString("org_id");
if (orgId == null || !orgId.matches("^[a-zA-Z0-9]{8,16}$")) {
throw new BadCredentialsException("org_id 格式非法");
}
// 2. 与当前请求头比对(网关已把 X-Org-Id 放入 SecurityContextHolder)
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String headerOrgId = attrs.getRequest().getHeader("X-Org-Id");
if (!orgId.equals(headerOrgId)) {
throw new AccessDeniedException("org_id 与请求头不一致");
}
// 3. 构造已认证令牌,把 org_id 放入权限集合,供后续 AuthorizationManager 使用
Collection<GrantedAuthority> authorities = Collections.singletonList(
new SimpleGrantedAuthority("ORG_" + orgId));
return new JwtAuthenticationToken(jwt, authorities);
}
@Override
public boolean supports(Class<?> authentication) {
return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication);
}
}
步骤三:注册到 Spring Security
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http,
OrgIdJwtAuthenticationProvider orgIdProvider) throws Exception {
http.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/org/**").access((authentication, context) ->
new AuthorizationDecision(
authentication.get().getAuthorities().stream()
.anyMatch(g -> g.getAuthority().startsWith("ORG_"))
)
)
.anyRequest().authenticated()
);
http.authenticationProvider(orgIdProvider);
http.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}
步骤四:异常处理(国内规范)
@RestControllerAdvice
public class AuthExceptionTranslator {
@ExceptionHandler({BadCredentialsException.class, AccessDeniedException.class})
public ResponseEntity<UnifiedResp<Void>> handle(AuthException e) {
return ResponseEntity.status(403)
.body(UnifiedResp.fail("A0301", "组织身份校验失败"));
}
}
通过以上四步,org_id 的格式、存在性、一致性、权限映射全部在 Spring Security 生命周期内完成,零侵入 Controller,符合国内大厂代码审计标准。
拓展思考
- 多组织切换场景:若用户同时属于多个 org,可把
org_id声明成数组,自定义JwtAuthenticationConverter生成多个JwtAuthenticationToken,再用AuthorizationManager做动态组织路由。 - 性能优化:国内高并发网关(如基于 Spring Cloud Gateway)可预解析 JWT 并把
org_id放入ServerWebExchange.getAttributes(),避免下游微服务重复验签,验签一次,多级复用。 - 密钥轮换:当使用JWK Set URL时,Nimbus 默认缓存 5 分钟;国内金融场景要求热轮换,可通过
CacheManager自定义TTL 1 分钟的JWKSource,实现零停机换钥。 - 审计留痕:在
OrgIdJwtAuthenticationProvider中把org_id写入 MDC,结合 SkyWalking 的traceId,可实现**“用户-组织-链路”** 三维审计,满足等保 2.0 要求。