Spring Cloud:Security OAuth2 自定義異常響應


對於客戶端開發或者網站開發而言,調用接口返回有統一的響應體,可以針對性的設計界面,代碼結構更加清晰,層次也更加分明。

默認異常響應

在使用 Spring Security Oauth2 登錄和鑒權失敗時,默認返回的異常信息如下:

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

這與我們返回的信息格式不一致。如果需要修改這種返回的格式,需要重寫相關異常處理類。這里我統一的是資源服務器(網關)的響應格式。

自定義異常響應

無效 token 異常類重寫

新增 AuthExceptionEntryPoint.java

@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint
{

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Map<String, Object> map = new HashMap<String, Object>();
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if(cause instanceof InvalidTokenException) {
                response.getWriter().write(ResultJsonUtil.build(
                        ResponseCodeConstant.REQUEST_FAILED,
                        ResponseStatusCodeConstant.OAUTH_TOKEN_FAILURE,
                        ResponseMessageConstant.OAUTH_TOKEN_ILLEGAL
                ));
            }else{
                response.getWriter().write(ResultJsonUtil.build(
                        ResponseCodeConstant.REQUEST_FAILED,
                        ResponseStatusCodeConstant.OAUTH_TOKEN_MISSING,
                        ResponseMessageConstant.OAUTH_TOKEN_MISSING
                ));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

權限不足異常類重寫

新增 CustomAccessDeniedHandler.java

@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException)
            throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            response.getWriter().write(ResultJsonUtil.build(
                    ResponseCodeConstant.REQUEST_FAILED,
                    ResponseStatusCodeConstant.OAUTH_TOKEN_DENIED,
                    ResponseMessageConstant.OAUTH_TOKEN_DENIED
            ));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

資源配置類中設置異常處理類

修改資源配置類 ResourceServerConfiguration.java

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
    resources.tokenExtractor(customTokenExtractor);
 resources.authenticationEntryPoint(authExceptionEntryPoint) .accessDeniedHandler(customAccessDeniedHandler);
}

自定義響應測試

示例代碼https://github.com/BNDong/spring-cloud-examples/tree/master/spring-cloud-zuul/cloud-zuul


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM