在使用 Spring Security Oauth2 登陸和鑑權失敗時,默認返回的異常信息以下:java
{ "error": "unauthorized", "error_description": "Full authentication is required to access this resource" }
這與咱們返回的信息格式不一致。若是須要修改這種返回的格式,須要重寫相關異常處理類。這裏我統一的是資源服務器(網關)的響應格式。git
新增 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服務器