我正在使用 Spring Boot OAuth 资源服务器 (JOSE) 来验证来自 Auth0 的 JWT。流程运行良好,除非我从 JWT 检查受众声明,如果失败,则返回 401 响应状态,但消息正文为空。
我自定义了 exceptionHandling 以发送消息正文,并且使用 authenticationEntryPoint 和 accessDeniedHandler 可以正常工作,但是对于 OAuth2TokenValidator 没有触发这些处理。
当观众验证错误发生时,我只想接收 401 和我为 401 自定义的消息正文。
这是我使用的代码:
public static class AudienceValidator implements OAuth2TokenValidator<Jwt> {
private Logger logger = LoggerFactory.getLogger(AudienceValidator.class);
private final String audience;
OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
public AudienceValidator(String audience) {
this.audience = audience;
}
public OAuth2TokenValidatorResult validate(Jwt jwt) {
logger.debug("validating audience: " + jwt.getAudience());
if (jwt.getAudience().contains(audience)) {
logger.debug("audience success");
return OAuth2TokenValidatorResult.success();
} else {
logger.debug("invalid audience");
return OAuth2TokenValidatorResult.failure(error);
}
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwtAuthenticationConverter(grantedAuthoritiesExtractor())
)
);
logger.debug("authenticatedOnly:"+authenticatedOnly);
if (authenticatedOnly) http.authorizeRequests().anyRequest().authenticated();
else http.authorizeRequests().anyRequest().permitAll();
http
.exceptionHandling()
.authenticationEntryPoint((request, response, e) -> {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json");
response.getWriter().write("{\"status\":401,\"error\":\"You are not authenticated.\",\"message\":\"\"}");
})
.accessDeniedHandler((request, response, e) -> {
response.setStatus(HttpStatus.FORBIDDEN.value());
response.setContentType("application/json");
response.getWriter().write("{\"status\":403,\"error\":\"You are not authorized.\",\"message\":\"\"}");
})
;
}