zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Linux内核文档:包含 kernel-doc 注释
    Linux内核文档:如何写符合 kernel-doc 规范的注释
    [记录点滴] 使用工具和命令对redis数据进行备份恢复
    聊聊CMDB的前世今生
    我是如何走上运维岗位的?谈谈新人入职运维发展的注意事项
    如何从生命周期的视角看待应用运维体系建设?
    标准化体系建设(下):如何建立基础架构标准化及服务化体系?
    标准化体系建设(上):如何建立应用标准化体系和模型?
    微服务架构时代,运维体系建设为什么要以“应用”为核心?
    lsattr命令
  • 原文地址:https://www.cnblogs.com/bndong/p/10275430.html
Copyright © 2011-2022 走看看