Spring Security Oauth2 自定义异常返回信息
开头引用
在使用Spring Security Oauth2登录和鉴权失败时,默认返回的异常信息如下
{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}
。它与我们自定义返回信息不一致,并且描述信息较少。那么如何自定义Spring Security Oauth2异常信息呢,下面我们简单实现以下。格式如下:
{
"code": 100100,
"data": null,
"message": "OAuth认证失败",
"success": false
}
文章中写的比较复杂。 梳理一下。
由于TokenEndpoint 中 已经添加了异常处理,自定义的全局异常处理处理优先级不如类级别的。项目中需要进行国际化还有自定义响应体。
@ExceptionHandler(Exception.class)
public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
if (logger.isWarnEnabled()) {
logger.warn("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
}
return getExceptionTranslator().translate(e);
}
看源码知道,只需要实现WebResponseExceptionTranslator类的translate 方法即可。
public ResponseEntity translate(Exception e) throws Exception {
if (e instanceof OAuth2Exception) {
int code = UserCode.OAUTH_ERROR;
String message = i18nHelper.getMessage(code);
return ResponseEntity.ok(Result.failure(code, message));
}
throw e;
}
去掉响应结果中泛型的限制,就可以返回任何自定义的对象。
ExceptionTranslator 的配置只需要在AuthorizationServerEndpointsConfigurer endpoints 后添加:
endpoints.exceptionTranslator(oAuthWebResponseExceptionTranslator);
