据报道,我们的授权服务器(Auth0)不会更改JWK集(也许会吗?)。为了提高性能,我们希望将来自远程身份验证服务器的密钥缓存的时间比DefaultJWKSetCache中5分钟的硬编码默认时间长得多,因为对于所有请求,令牌和密钥都需要使用这些密钥来验证令牌。被请求的时间会增加大量的延迟。请注意,JWT解码器库类为final
。
减少对授权服务器的请求数量的阻力最小的路径似乎是代理将处理缓存的本地路由。有更好的方法吗?
版本:Spring Boot 2.2.5(Spring 5.2)
// Relevant imports (omitted) from:
// import org.springframework.security.oauth2.core
// import org.springframework.security.oauth2.jwt
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${auth0.audience}")
private String audience;
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuer;
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.cors()
.and()
.csrf()
.disable()
.oauth2ResourceServer()
.jwt();
// @formatter:on
}
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.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;
}
}