Spring 如何在OAuth2TokenValidatorResult中捕获自定义异常? 类验证程序实现OAuth2TokenValidator{ OAuth2Error error=新的OAuth2Error(“401”,“身份验证异常”,null); @鬼鬼祟祟 @凌驾 公共OAuth2TokenValidatorResult验证(Jwt Jwt){ 如果(…){ 返回OAuth2TokenValidatorResult.failure(错误); } 如果(…){ 抛出新的禁止异常(“未找到请求的角色”); } 返回OAuth2TokenValidatorResult.success(); } } @资料 公共类禁止异常扩展异常{ 私有http状态; 私钥错误; 公共禁止例外{ 超级(“缺少所需角色”); this.status=HttpStatus.FORBIDDEN; this.error=apierro.builder().timestamp(LocalDateTime.now()).status(HttpStatus.FORBIDDEN.value()).message(“缺少必需的角色”).build(); } } @ExceptionHandler(禁止Exception.class) 受保护的响应HandLeapeException(禁止异常ex){ 返回响应性 .status(例如getStatus()) .body(例如getError()); }
大家好。我想处理jwt验证错误。如果发生错误,validate方法将返回401错误。它为我安排了第一个条件。在第二种情况下,我应该抛出403错误,为此我需要重写ResponseEntityExceptionHandler(可能是AuthenticationFailureHandler)中的方法。在本例中,所有此类错误OAuth2TokenValidatorResult.failure都将被捕获并返回403,但我需要401和403。我试图在@ControllerAdvice中为它编写一个自定义的禁止异常和@ExceptionHandler,但在这种情况下,我仍然得到了401而不是403。如何解决这个问题?提前谢谢Spring 如何在OAuth2TokenValidatorResult中捕获自定义异常? 类验证程序实现OAuth2TokenValidator{ OAuth2Error error=新的OAuth2Error(“401”,“身份验证异常”,null); @鬼鬼祟祟 @凌驾 公共OAuth2TokenValidatorResult验证(Jwt Jwt){ 如果(…){ 返回OAuth2TokenValidatorResult.failure(错误); } 如果(…){ 抛出新的禁止异常(“未找到请求的角色”); } 返回OAuth2TokenValidatorResult.success(); } } @资料 公共类禁止异常扩展异常{ 私有http状态; 私钥错误; 公共禁止例外{ 超级(“缺少所需角色”); this.status=HttpStatus.FORBIDDEN; this.error=apierro.builder().timestamp(LocalDateTime.now()).status(HttpStatus.FORBIDDEN.value()).message(“缺少必需的角色”).build(); } } @ExceptionHandler(禁止Exception.class) 受保护的响应HandLeapeException(禁止异常ex){ 返回响应性 .status(例如getStatus()) .body(例如getError()); },spring,exception,oauth-2.0,Spring,Exception,Oauth 2.0,大家好。我想处理jwt验证错误。如果发生错误,validate方法将返回401错误。它为我安排了第一个条件。在第二种情况下,我应该抛出403错误,为此我需要重写ResponseEntityExceptionHandler(可能是AuthenticationFailureHandler)中的方法。在本例中,所有此类错误OAuth2TokenValidatorResult.failure都将被捕获并返回403,但我需要401和403。我试图在@ControllerAdvice中为它编写一个自定义的禁
class Validator implements OAuth2TokenValidator<Jwt> {
OAuth2Error error = new OAuth2Error("401", "Authentication exception", null);
@SneakyThrows
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
if (... ){
return OAuth2TokenValidatorResult.failure(error);
}
if (...){
throw new ForbiddenException("Requested roles not found");
}
return OAuth2TokenValidatorResult.success();
}
}
@Data
public class ForbiddenException extends Exception {
private HttpStatus status;
private ApiError error;
public ForbiddenException() {
super("Required roles are missing");
this.status = HttpStatus.FORBIDDEN;
this.error = ApiError.builder().timestamp(LocalDateTime.now()).status(HttpStatus.FORBIDDEN.value()).message("Required roles are missing").build();
}
}
@ExceptionHandler(ForbiddenException.class)
protected ResponseEntity<ApiError> handleApiException(ForbiddenException ex) {
return ResponseEntity
.status(ex.getStatus())
.body(ex.getError());
}