You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.5.2中如何为/oauth/token API返回自定义状态码

解决Spring Boot OAuth2 /oauth/token接口自定义状态码返回问题

问题根源

Spring Security OAuth2在认证流程中会统一捕获所有认证相关异常,并默认转换为401状态码返回,导致你抛出的LBCLServiceException被覆盖,无法返回自定义状态码。

解决方案步骤

1. 确保自定义异常携带状态码信息

先确认你的LBCLServiceException类包含状态码字段,方便后续获取:

public class LBCLServiceException extends RuntimeException {
    private final int statusCode;
    private final String errorCode;

    public LBCLServiceException(String errorCode, String message, int statusCode) {
        super(message);
        this.errorCode = errorCode;
        this.statusCode = statusCode;
    }

    // getter方法
    public int getStatusCode() {
        return statusCode;
    }

    public String getErrorCode() {
        return errorCode;
    }
}

(抛出异常时传入对应状态码:INACTIVE_ACCOUNT传605,TEMPORARY_PASSWORD_EXPIRED传705)

2. 自定义OAuth2异常转换器

实现WebResponseExceptionTranslator,将自定义异常转换为OAuth2格式响应并设置自定义状态码:

@Component
public class CustomOauth2ExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        if (e instanceof LBCLServiceException) {
            LBCLServiceException serviceException = (LBCLServiceException) e;
            CustomOauth2Exception oauth2Exception = new CustomOauth2Exception(
                    serviceException.getMessage(),
                    serviceException.getErrorCode()
            );
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            return new ResponseEntity<>(oauth2Exception, headers, HttpStatus.valueOf(serviceException.getStatusCode()));
        }
        // 处理其他OAuth2默认异常
        DefaultWebResponseExceptionTranslator defaultTranslator = new DefaultWebResponseExceptionTranslator();
        return defaultTranslator.translate(e);
    }

    // 自定义OAuth2Exception,用于返回自定义错误码
    private static class CustomOauth2Exception extends OAuth2Exception {
        private final String errorCode;

        public CustomOauth2Exception(String msg, String errorCode) {
            super(msg);
            this.errorCode = errorCode;
        }

        @Override
        public Map<String, String> getAdditionalInformation() {
            Map<String, String> info = new HashMap<>();
            info.put("error_code", errorCode);
            info.put("message", getMessage());
            return info;
        }

        @Override
        public String getOAuth2ErrorCode() {
            return errorCode;
        }
    }
}

3. 在AuthorizationServer配置中替换异常转换器

修改你的AuthorizationServerConfigurerAdapter实现类,配置自定义异常转换器:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private CustomOauth2ExceptionTranslator customOauth2ExceptionTranslator;

    @Autowired
    private Oauth2UserServiceImpl oauth2UserServiceImpl;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .userDetailsService(oauth2UserServiceImpl)
                // 设置自定义异常转换器
                .exceptionTranslator(customOauth2ExceptionTranslator);
        // 其他原有配置(如tokenStore、clientDetailsService等)
    }

    // 其他配置方法(如客户端信息、安全约束等)
}

4. 验证效果

当用户状态非Active时,抛出new LBCLServiceException(INACTIVE_ACCOUNT, "This vendor has been deactivated.", 605),/oauth/token接口会返回605状态码,响应体包含自定义错误码和信息;临时密码过期时抛出对应705的异常,接口返回705状态码。


内容的提问来源于stack exchange,提问作者Lakshmi Kanchana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:43:21