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

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

默認異常響應

在使用 Spring Security Oauth2 登陸和鑑權失敗時,默認返回的異常信息以下:java

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

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

自定義異常響應

無效 token 異常類重寫

新增 AuthExceptionEntryPoint.javagithub

@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.javaspring

@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.javajson

@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服務器

相關文章
相關標籤/搜索