Spring Security Oauth2 自定义异常返回信息

时间:2025-02-13 21:12:01
背景

在使用Spring Security OAuth2进行登录和鉴权时,系统默认返回的异常信息可能不符合我们的需求。默认的异常信息通常比较简洁,并且格式可能与我们自定义的API响应风格不一致。为了解决这个问题,我们需要自定义Spring Security OAuth2的异常返回信息。

默认异常信息

默认情况下,OAuth2认证失败时,会返回类似以下的JSON响应:

{
  "error": "unauthorized",
  "error_description": "Full authentication is required to access this resource"
}

这种格式可能并不符合我们的业务需求和API设计,它与我们自定义返回信息不一致,并且描述信息较少。我们想要的返回结果是:

{
    "code": 100100,
    "data": null,
    "message": "OAuth认证失败",
    "success": false
}

自定义异常信息

为了自定义异常返回信息,我们可以实现WebResponseExceptionTranslator接口,并重写其translate方法。在该方法中,我们可以根据捕获的异常类型,返回自定义的响应体。

以下是一个简单的示例实现:

import ;
import ;
import ..OAuth2Exception;
import .;

// 假设我们有一个Result类来包装响应体
public class CustomResponseExceptionTranslator implements WebResponseExceptionTranslator {

    private final I18nHelper i18nHelper; // 假设的国际化助手类

    public CustomResponseExceptionTranslator(I18nHelper i18nHelper) {
        this.i18nHelper = i18nHelper;
    }

    @Override
    public ResponseEntity<Object> translate(Exception e) throws Exception {
        if (e instanceof OAuth2Exception) {
            OAuth2Exception oauthException = (OAuth2Exception) e;
            int code = UserCode.OAUTH_ERROR; // 自定义的错误码
            String message = (code, ()); // 国际化错误消息
            // 构造自定义的响应体
            Result result = (code, message);
            return new ResponseEntity<>(result, );
        }
        throw e; // 对于非OAuth2Exception异常,直接抛出
    }
}

// 假设的Result类
public class Result {
    private int code;
    private Object data;
    private String message;
    private boolean success;

    // ... 省略getter和setter方法

    public static Result failure(int code, String message) {
        Result result = new Result();
        (code);
        (message);
        (false);
        return result;
    }

    // ... 省略其他方法
}
配置异常转换器

配置自定义的异常转换器需要在配置OAuth2授权服务器时添加以下代码:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    // ... 其他配置 ...

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // ... 其他配置 ...
        CustomResponseExceptionTranslator oAuthWebResponseExceptionTranslator = new CustomResponseExceptionTranslator(i18nHelper); // 实例化异常转换器
        (oAuthWebResponseExceptionTranslator); // 配置异常转换器
    }

    // ... 其他配置 ...
}
总结

通过实现WebResponseExceptionTranslator接口并配置到OAuth2授权服务器中,我们可以轻松地自定义OAuth2认证失败时的异常返回信息。这种方式不仅允许我们自定义响应体的格式,还可以结合国际化功能,提供更加友好的错误信息。