使用 NimbusJwtDecoder 时如何切换 JWS 算法?
解读
在国内 Spring Security 生产环境面试中,面试官问“如何切换 JWS 算法”并不是想听你背诵构造方法,而是考察三点:
- 是否知道 NimbusJwtDecoder 内部把算法校验委托给 ConfigurableJWTProcessor<SecurityContext>;
- 能否在不破坏 Spring Boot 自动装配的前提下,用 JwtDecoderCustomizer 或 @Bean 覆盖默认算法集合;
- 是否意识到 国密 SM2/SM3 等算法在 Nimbus 原生不支持,需要扩展 JWSAlgorithm 并注入自定义 JWSKeySelector。
一句话:要“换算法”,必须先“换处理器”,再“换验证器”,最后“换解码器”。
知识点
- NimbusJwtDecoder 唯一构造参数是 ConfigurableJWTProcessor,算法白名单由 JWSKeySelector 控制;
- JWSAlgorithm 枚举只包含 RS256/384/512、ES256/384/512、PS256/384/512、HS256/384/512 等国际标准,国密算法不在其中;
- Spring Boot 2.5+ 提供的 JwtDecoderCustomizer<OAuth2ResourceServerJwkJwtDecoderBuilder> 是官方推荐的“无侵入”修改点;
- 若使用 jwk-set-uri,Spring 默认构建 RemoteJWKSet,此时算法切换必须保证 JWK 的 alg 字段与 JWSKeySelector 白名单双向匹配,否则抛出 BadJWSException;
- 切换成 对称密钥 HS256 时,必须关闭 JWK 公钥拉取,直接调用 NimbusJwtDecoder.withSecretKey();
- 国内等保测评要求 SM2/SM3 时,需自定义 JWSAlgorithm 实例(非枚举值),并注册 JWSKeySelector 的 extend 实现,否则启动即报 IllegalArgumentException: Unsupported JWS algorithm 'SM2'。
答案
步骤一:关闭 Spring Boot 自动装配的 JwtDecoder,手动构造 ConfigurableJWTProcessor
ConfigurableJWTProcessor<SecurityContext> processor = new DefaultJWTProcessor<>();
步骤二:创建允许目标算法的 JWSKeySelector
// 例:从 RS256 切换到 ES256
JWSKeySelector<SecurityContext> jwsKeySelector =
new JWSVerificationKeySelector<>(JWSAlgorithm.ES256, jwkSource);
processor.setJWSKeySelector(jwsKeySelector);
步骤三:用处理器构建解码器并注入容器
@Bean
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
ConfigurableJWTProcessor<SecurityContext> processor = new DefaultJWTProcessor<>();
JWSKeySelector<SecurityContext> selector =
new JWSVerificationKeySelector<>(JWSAlgorithm.ES256, jwkSource);
processor.setJWSKeySelector(selector);
return new NimbusJwtDecoder(processor);
}
若仅想微调算法而不想写完整 Bean,可在 application.yml 保留 jwk-set-uri,然后提供 JwtDecoderCustomizer:
@Bean
public JwtDecoderCustomizer<OAuth2ResourceServerJwkJwtDecoderBuilder> customizer() {
return builder -> builder.jwsAlgorithm(JWSAlgorithm.ES256);
}
注意:一旦切换为 HS256 等对称算法,必须使用
NimbusJwtDecoder.withSecretKey(mySecretKey).jwsAlgorithm(MacAlgorithm.HS256).build()
且不能再配置 jwk-set-uri,否则 Spring 会强制走远程 JWK,启动报错。
拓展思考
- 国内金融项目要求 双证书 + SM2,此时需引入 国密 JCE 提供者(如 BJCA、江南天安),自定义 JWSAlgorithm.parse("SM2") 并扩展 JWSKeySelector,在 select 方法里返回 SM2PublicKey;同时把 NimbusJwtDecoder 的 JWTProcessor 完全替换掉,Spring Security 5.x 暂无官方支持,需自行维护一个 Sm2JwtDecoder 实现。
- 多租户场景下不同租户使用不同算法,可在 JWSKeySelector 里根据 JWT 的 iss claim 动态返回 RSAKey 或 ECKey,实现算法路由;此时 NimbusJwtDecoder 必须是原型作用域,避免线程安全问题。
- 切换算法后,旧 Token 仍可能存活,需要结合 JwtIssuerValidator + JwtTimestampValidator 做灰度发布,或者直接在 JWK 端点把旧算法对应的 kid 删除,强制客户端重新获取新 Token。