Spring Cloud:Security OAuth2 自定义异常响应

Posted geass-jango

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于Spring Cloud:Security OAuth2 自定义异常响应的主要内容,如果未能解决你的问题,请参考以下文章

Spring Cloud Security[微服务安全](一)初识Spring Cloud Security和OAuth2.0

Spring Cloud 值Spring-Security

如何使用 redis 使用 spring-security-oauth2 持久化令牌

Spring cloud eureka 添加 spring-security

无法修复 spring-security-oauth2-resource-server 上的漏洞

使用 spring-session 和 spring-cloud-security 时,OAuth2ClientContext (spring-security-oauth2) 不会保留在 Redis