我有以下代码...
public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
private final String audience;
public AudienceValidator(String audience) {
this.audience = audience;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
if (jwt.getAudience().contains(audience)) {
return OAuth2TokenValidatorResult.success();
} else {
return OAuth2TokenValidatorResult.failure(error);
}
}
}
@EnableWebSecurity
public class SecurityConfig{
@Value("${auth0.audience}")
private String audience;
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuer;
@Bean
public 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;
}
@Bean …Run Code Online (Sandbox Code Playgroud) 当 jwt 令牌无效或过期时,为什么不调用此开始方法?当令牌为空时会调用它。奇怪的是,在调试时我发现当令牌无效或过期时,会调用 BearerTokenAuthenticationEntryPoint.commence() 方法。这个类是标准java库的一部分,并且是最终的,所以不能扩展。但它实现了与我实现相同的接口 - AuthenticationEntryPoint,但我的开始方法仍然没有被调用。仅当令牌为空时才会调用它。
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
public CustomAuthenticationEntryPoint() {
}
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException authenticationException) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
HttpStatus status = HttpStatus.UNAUTHORIZED;
final Map<String, Object> body = new HashMap<>();
body.put("status", status.name());
body.put("statusCode", status.value());
body.put("message", "You need to login first in order to perform this action");
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), body);
}
}
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> …Run Code Online (Sandbox Code Playgroud)