對於客戶端開發或者網站開發而言,調用接口返回有統一的響應體,可以針對性的設計界面,代碼結構更加清晰,層次也更加分明。
默認異常響應
在使用 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