我发现有时我仍然收到 Auth0 的超时消息。看起来他们对 JWK 请求的响应速度很慢,需要更多的等待时间。在我的项目中导致失败的超时是 com.nimbusds.jose.jwk.source.RemoteJWKSet 中定义的两个常量。
public static final int DEFAULT_HTTP_CONNECT_TIMEOUT = 500;
public static final int DEFAULT_HTTP_READ_TIMEOUT = 500;
所以我提出了一个非常丑陋的解决方案,它对我有用,直到有人将这些常量转化为属性。
假设您正在使用 Auth0 指南https://auth0.com/docs/quickstart/backend/java-spring-security5/01-authorization https://auth0.com/docs/quickstart/backend/java-spring-security5/01-authorization并且您将“jwk-set-uri:https://your-domain/.well-known/jwks.json”键添加到您的属性中,因为 com.nimbusds.jose.jwk.source.RemoteJWKSet 不是我可以用我自己的自定义实现替换,或者无法使用 AOP 替换超时参数,因为这些参数是在构造函数中传递的,我必须复制一些内容来制作我自己的所需类版本。
SOLUTION
我制作了以下类的自己版本,只需复制原始代码并在需要的地方进行自定义:
- com.nimbusds.jose.jwk.source.RemoteJWKSet(自定义增加
超时常数)
public static final int DEFAULT_HTTP_CONNECT_TIMEOUT = 1000;
public static final int DEFAULT_HTTP_READ_TIMEOUT = 1000;
- org.springframework.security.oauth2.jwt.JwtDecoders(自定义创建我的自定义版本的 RemoteJWKSet 的实例)
private static JwtDecoder withProviderConfiguration(Map<String, Object> configuration, String issuer) {
CustomJwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer);
OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefaultWithIssuer(issuer);
String jwkSetUri = configuration.get("jwks_uri").toString();
CustomRemoteJWKSet<SecurityContext> jwkSource = new CustomRemoteJWKSet<>(url(jwkSetUri));
Set<SignatureAlgorithm> signatureAlgorithms = CustomJwtDecoderProviderConfigurationUtils
.getSignatureAlgorithms(jwkSource);
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
.jwsAlgorithms((algs) -> algs.addAll(signatureAlgorithms)).build();
jwtDecoder.setJwtValidator(jwtValidator);
return jwtDecoder;
}
- org.springframework.security.oauth2.jwt.JwtDecoderProviderConfigurationUtils(这没有自定义,但我必须复制它,因为它从包外部看不到)
然后我只是用自定义的解码器替换了我的配置中的解码器
@Bean
public JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
CustomJwtDecoders.fromOidcIssuerLocation(issuer);
OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(
withIssuer, audienceValidator);
jwtDecoder.setJwtValidator(withAudience);
return jwtDecoder;
}
到目前为止,一切顺利,没有更多的超时。