标签:conf zed uil string map codec cloud lan red
# 默认异常响应
在使用 Spring Security Oauth2 登录和鉴权失败时,默认返回的异常信息如下:
这与我们返回的信息格式不一致。如果需要修改这种返回的格式,需要重写相关异常处理类。这里我统一的是资源服务器(网关)的响应格式。
# 自定义异常响应
## 无效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
修改资源配置类 ResourceServerConfiguration.java
示例代码:https://github.com/BNDong/spring-cloud-examples/tree/master/spring-cloud-zuul/cloud-zuul
Spring Cloud:Security OAuth2 自定义异常响应
标签:conf zed uil string map codec cloud lan red
原文地址:https://www.cnblogs.com/geass-jango/p/11022790.html