Spring Security OAuth2 认证服务器自定义异常处理
认证服务器默认返回的数据格式如下:
{
"error": "unsupported_grant_type",
"error_description": "Unsupported grant type: password1"
}
上面的返回结果很不友好,而且前端代码也很难判断是什么错误,所以我们需要对返回的错误进行统一的异常处理
默认的异常处理器
默认情况是使用WebResponseExceptionTranslator
接口的实现类DefaultWebResponseExceptionTranslator
对抛出的异常进行处理;所以可以通过WebResponseExceptionTranslator
接口入手,实现接口的方法对异常进行处理。
定义继承OAuth2Exception的异常类
/**
* @Description: 异常处理类
* @Package: cn.appblog.security.oauth2.exception.UserOAuth2Exception
* @Version: 1.0
*/
@JsonSerialize(using = UserOAuth2ExceptionSerializer.class)
public class UserOAuth2Exception extends OAuth2Exception {
private Integer status = 400;
public UserOAuth2Exception(String message, Throwable t) {
super(message, t);
status = ((OAuth2Exception) t).getHttpErrorCode();
}
public UserOAuth2Exception(String message) {
super(message);
}
@Override
public int getHttpErrorCode() {
return status;
}
}
定义序列化实现类
/**
* @Description: 序列化异常类
* @Package: cn.appblog.security.oauth2.exception.BootOAuthExceptionJacksonSerializer
* @Version: 1.0
*/
public class UserOAuth2ExceptionSerializer extends StdSerializer<UserOAuth2Exception> {
protected UserOAuth2ExceptionSerializer() {
super(UserOAuth2Exception.class);
}
@Override
public void serialize(UserOAuth2Exception e, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {
generator.writeStartObject();
generator.writeObjectField("status", e.getHttpErrorCode());
String message = e.getMessage();
if (message != null) {
message = HtmlUtils.htmlEscape(message);
}
generator.writeStringField("message", message);
if (e.getAdditionalInformation() != null) {
for (Map.Entry<String, String> entry : e.getAdditionalInformation().entrySet()) {
String key = entry.getKey();
String add = entry.getValue();
generator.writeStringField(key, add);
}
}
generator.writeEndObject();
}
}
自定义实现异常转换类
/**
* @Description: 资源服务器异常自定义捕获
* @Package: cn.appblog.security.oauth2.exception.OAuth2ServerWebResponseExceptionTranslator
* @Version: 1.0
*/
@Component
public class UserOAuth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator {
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(e);
Exception ase = (OAuth2Exception) this.throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
//异常链中有OAuth2Exception异常
if (ase != null) {
return this.handleOAuth2Exception((OAuth2Exception) ase);
}
//身份验证相关异常
ase = (AuthenticationException) this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
if (ase != null) {
return this.handleOAuth2Exception(new UserOAuth2WebResponseExceptionTranslator.UnauthorizedException(e.getMessage(), e));
}
//异常链中包含拒绝访问异常
ase = (AccessDeniedException) this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
if (ase instanceof AccessDeniedException) {
return this.handleOAuth2Exception(new UserOAuth2WebResponseExceptionTranslator.ForbiddenException(ase.getMessage(), ase));
}
//异常链中包含Http方法请求异常
ase = (HttpRequestMethodNotSupportedException) this.throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
if (ase instanceof HttpRequestMethodNotSupportedException) {
return this.handleOAuth2Exception(new UserOAuth2WebResponseExceptionTranslator.MethodNotAllowed(ase.getMessage(), ase));
}
return this.handleOAuth2Exception(new UserOAuth2WebResponseExceptionTranslator.ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));
}
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {
int status = e.getHttpErrorCode();
HttpHeaders headers = new HttpHeaders();
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
if (status == HttpStatus.UNAUTHORIZED.value() || e instanceof InsufficientScopeException) {
headers.set("WWW-Authenticate", String.format("%s %s", "Bearer", e.getSummary()));
}
UserOAuth2Exception exception = new UserOAuth2Exception(e.getMessage(), e);
ResponseEntity<OAuth2Exception> response = new ResponseEntity(exception, headers, HttpStatus.valueOf(status));
return response;
}
private static class MethodNotAllowed extends OAuth2Exception {
public MethodNotAllowed(String msg, Throwable t) {
super(msg, t);
}
@Override
public String getOAuth2ErrorCode() {
return "method_not_allowed";
}
@Override
public int getHttpErrorCode() {
return 405;
}
}
private static class UnauthorizedException extends OAuth2Exception {
public UnauthorizedException(String msg, Throwable t) {
super(msg, t);
}
@Override
public String getOAuth2ErrorCode() {
return "unauthorized";
}
@Override
public int getHttpErrorCode() {
return 401;
}
}
private static class ServerErrorException extends OAuth2Exception {
public ServerErrorException(String msg, Throwable t) {
super(msg, t);
}
@Override
public String getOAuth2ErrorCode() {
return "server_error";
}
@Override
public int getHttpErrorCode() {
return 500;
}
}
private static class ForbiddenException extends OAuth2Exception {
public ForbiddenException(String msg, Throwable t) {
super(msg, t);
}
@Override
public String getOAuth2ErrorCode() {
return "access_denied";
}
@Override
public int getHttpErrorCode() {
return 403;
}
}
}
将自定义异常处理类添加到认证服务器配置
/**
* @Description: @EnableAuthorizationServer注解开启OAuth2授权服务机制
* @Package: cn.appblog.security.oauth2.config.AuthorizationServerConfigure
* @Version: 1.0
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {
@Autowired
private WebResponseExceptionTranslator webResponseExceptionTranslator;
/**
* 用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
...
endpoints.exceptionTranslator(webResponseExceptionTranslator);
...
}
}
本文转载参考 原文 并加以调试
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/20/spring-security-oauth2-authentication-server-custom-exception-handling/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
Spring Security OAuth2 认证服务器自定义异常处理
认证服务器默认返回的数据格式如下:
{
"error": "unsupported_grant_type",
"error_description": "Unsupported……
文章目录
关闭
共有 0 条评论