Spring Security OAuth2 认证服务器自定义异常处理

前言

Spring Security OAuth2 认证失败的格式如下

{
    "error": "unsupported_grant_type",
    "error_description": "Unsupported grant type: refresh_token1"
}

这个返回是很不友好的,特别是在前后端分离的时候,前端一般是根据我们的返回码进行处理,所以我们还得自定义我们的异常处理

WebResponseExceptionTranslator

在 AuthorizationServerEndpointsConfigurer端点配置类有一个 WebResponseExceptionTranslator异常转换器。

WebResponseExceptionTranslator只有一个translate方法,很明显,这个方法就是用来转换异常的

public interface WebResponseExceptionTranslator<T> {
	
	ResponseEntity<T> translate(Exception e) throws Exception;

}

它就是专门用于处理异常转换的,我们要自定义异常很简单,创建一个类来实现WebResponseExceptionTranslator接口,然后进行配置即

自定义异常处理

1、自定义我们响应实体类

定义一个我们需要格式的响应实体类,这个实体类我们以json的格式返回

/**
 * 统一的返回实体
 */
@Data
@NoArgsConstructor
public class MyResponseResult<T>  {

    /**
     * 响应码
     */
    private String code;

    /**
     * 响应结果消息
     */
    private String msg;

    /**
     * 响应数据
     */
    private T data;

    protected MyResponseResult(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> MyResponseResult<T> failed(String resultCode, String resultMsg) {
        return new MyResponseResult<T>(resultCode, resultMsg, null);
    }

    public static <T> MyResponseResult<T> failed(String message) {
        return new MyResponseResult<T>(ResultCode.FAILED.getCode(), message, null);
    }

    public static <T> MyResponseResult<T> failed(T data) {
        return new MyResponseResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), data);
    }

}

2、定义响应结果枚举类

/**
 * 响应结果枚举
 */
@Getter
@AllArgsConstructor
public enum ResultCode {

    SUCCESS("200", "操作成功"),
    FAILED("500", "操作失败"),
    AUTH_FAIL("10001", "认证失败"),
    INVALID_TOKEN("10002", "token无效"),
    NONSUPPORT_GRANT_TYPE("10003", "授权类型不支持"),
    ;

    private final String code;

    private final String msg;

}

3、自定义异常转换类

/**
 * 自定义异常转换
 */
@Slf4j
public class MyExtendOAuth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {

    public static final int FAIL_CODE = 500;

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        log.error("认证服务器认证异常:{}", e.getMessage());
        //对异常进行转换
        if (e instanceof UnsupportedGrantTypeException){
            return ResponseEntity.status(FAIL_CODE).contentType(MediaType.APPLICATION_JSON)
                    .body(MyResponseResult.failed(ResultCode.NONSUPPORT_GRANT_TYPE.getCode(), ResultCode.NONSUPPORT_GRANT_TYPE.getMsg()));
        }
        if (e instanceof InvalidTokenException) {
            return ResponseEntity.status(FAIL_CODE).contentType(MediaType.APPLICATION_JSON)
                    .body(MyResponseResult.failed(ResultCode.INVALID_TOKEN.getCode(),ResultCode.INVALID_TOKEN.getMsg()));
        }
        return ResponseEntity.status(FAIL_CODE).contentType(MediaType.APPLICATION_JSON)
                .body(MyResponseResult.failed(ResultCode.AUTH_FAIL.getCode(),ResultCode.AUTH_FAIL.getMsg()));
    }

}

4、配置自定义异常转换器

在AuthorizationServerConfig配置文件的configure(AuthorizationServerEndpointsConfigurer endpoints)方法加下下面这行配置即可

//指定异常转换器
        endpoints.exceptionTranslator(new MyExtendOAuth2ResponseExceptionTranslator());

5、测试

使用一个不存在的grant_type请求/oauth/token,已经返回我们自定义的异常响应了

{
    "code": "10003",
    "msg": "授权类型不支持",
    "data": null
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值