当前位置:   article > 正文

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

webresponseexceptiontranslator

前言

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

{
    "error": "unsupported_grant_type",
    "error_description": "Unsupported grant type: refresh_token1"
}
  • 1
  • 2
  • 3
  • 4

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

WebResponseExceptionTranslator

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

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

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

}
  • 1
  • 2
  • 3
  • 4
  • 5

它就是专门用于处理异常转换的,我们要自定义异常很简单,创建一个类来实现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);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

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;

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

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()));
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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

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

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

5、测试

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

{
    "code": "10003",
    "msg": "授权类型不支持",
    "data": null
}
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号