SpringCloud Alibaba实战二十七 - Oauth2认证服务器自定义异常

简介: 今天内容主要是解决一位粉丝提的问题:在使用 Spring Security OAuth2 时如何自定义认证服务器返回异常。

前言


今天内容主要是解决一位粉丝提的问题:在使用 Spring Security OAuth2 时如何自定义认证服务器返回异常。


那么首先我们先以 Password模式为例看看在认证时会出现哪些异常情况。


授权模式错误


这里我们故意将授权模式 password 修改成 password1,认证服务器返回如下所示的异常


{
"error": "unsupported_grant_type",
"error_description": "Unsupported grant type: password1"}


密码错误


在认证时故意输错 usernamepassword 会出现如下异常错误:


{
"error": "invalid_grant",
"error_description": "Bad credentials"}


客户端错误


在认证时故意输错 client_idclient_secret


{
"error": "invalid_client",
"error_description": "Bad client credentials"}


上面的返回结果很不友好,而且前端代码也很难判断是什么错误,所以我们需要对返回的错误进行统一的异常处理,让其返回统一的异常格式。


问题剖析


如果只关注解决方案,可以直接跳转到解决方案模块!


OAuth2Exception异常处理


在Oauth2认证服务器中认证逻辑最终调用的是 TokenEndpoint#postAccessToken()方法,而一旦认证出现 OAuth2Exception异常则会被 handleException()捕获到异常。如下图展示的是当出现用户密码异常时debug截图:


1.png


认证服务器在捕获到 OAuth2Exception后会调用 WebResponseExceptionTranslator#translate()方法对异常进行翻译处理。


默认的翻译处理实现类是 DefaultWebResponseExceptionTranslator,处理完成后会调用 handleOAuth2Exception()方法将处理后的异常返回给前端,这就是我们之前看到的异常效果。


处理方法


熟悉Oauth2套路的同学应该知道了如何处理此类异常,就是「自定义一个异常翻译类让其返回我们需要的自定义格式,然后将其注入到认证服务器中。」


但是这种处理逻辑只能解决 OAuth2Exception异常,即前言部分中的「授权模式异常」「账号密码类的异常」,并不能解决我们客户端的异常。


客户端异常处理


客户端认证的异常是发生在过滤器 ClientCredentialsTokenEndpointFilter上,其中有后置添加失败处理方法,最后把异常交给 OAuth2AuthenticationEntryPoint这个所谓认证入口处理。执行顺序如下所示:


2.png


然后跳转到父类的 AbstractOAuth2SecurityExceptionHandler#doHandle()进行处理:


3.png


最终由 DefaultOAuth2ExceptionRenderer#handleHttpEntityResponse()方法将异常输出给客户端


4.png


处理方法


通过上面的分析我们得知客户端的认证失败异常是过滤器

ClientCredentialsTokenEndpointFilter转交给 OAuth2AuthenticationEntryPoint得到响应结果的,既然这样我们就可以重写 ClientCredentialsTokenEndpointFilter然后使用自定义的 AuthenticationEntryPoint替换原生的 OAuth2AuthenticationEntryPoint,在自定义 AuthenticationEntryPoint处理得到我们想要的异常数据。


解决方案


为了解决上面这些异常,我们首先需要编写不同异常的错误代码:ReturnCode.java


CLIENT_AUTHENTICATION_FAILED(1001,"客户端认证失败"),
USERNAME_OR_PASSWORD_ERROR(1002,"用户名或密码错误"),
UNSUPPORTED_GRANT_TYPE(1003, "不支持的认证模式");


OAuth2Exception异常


如上所说我们编写一个自定义异常翻译类

CustomWebResponseExceptionTranslator


@Slf4jpublicclassCustomWebResponseExceptionTranslatorimplementsWebResponseExceptionTranslator {
@OverridepublicResponseEntity<ResultData<String>>translate(Exceptione) throwsException {
log.error("认证服务器异常",e);
ResultData<String>response=resolveException(e);
returnnewResponseEntity<>(response, HttpStatus.valueOf(response.getHttpStatus()));
    }
/*** 构建返回异常* @param e exception* @return*/privateResultData<String>resolveException(Exceptione) {
// 初始值 500ReturnCodereturnCode=ReturnCode.RC500;
inthttpStatus=HttpStatus.UNAUTHORIZED.value();
//不支持的认证方式if(einstanceofUnsupportedGrantTypeException){
returnCode=ReturnCode.UNSUPPORTED_GRANT_TYPE;
//用户名或密码异常        }elseif(einstanceofInvalidGrantException){
returnCode=ReturnCode.USERNAME_OR_PASSWORD_ERROR;
        }
ResultData<String>failResponse=ResultData.fail(returnCode.getCode(), returnCode.getMessage());
failResponse.setHttpStatus(httpStatus);
returnfailResponse;
    }
}


然后在认证服务器配置类中注入自定义异常翻译类


@Overridepublicvoidconfigure(AuthorizationServerEndpointsConfigurerendpoints) throwsException {
//如果需要使用refresh_token模式则需要注入userDetailServiceendpoints            .authenticationManager(this.authenticationManager)
            .userDetailsService(userDetailService)
//                注入tokenGranter            .tokenGranter(tokenGranter);
//注入自定义的tokenservice,如果不使用自定义的tokenService那么就需要将tokenServce里的配置移到这里//                .tokenServices(tokenServices());// 自定义异常转换类endpoints.exceptionTranslator(newCustomWebResponseExceptionTranslator());
}


客户端异常


重写客户端认证过滤器,不使用默认的 OAuth2AuthenticationEntryPoint处理异常


publicclassCustomClientCredentialsTokenEndpointFilterextendsClientCredentialsTokenEndpointFilter {
privatefinalAuthorizationServerSecurityConfigurerconfigurer;
privateAuthenticationEntryPointauthenticationEntryPoint;
publicCustomClientCredentialsTokenEndpointFilter(AuthorizationServerSecurityConfigurerconfigurer) {
this.configurer=configurer;
    }
@OverridepublicvoidsetAuthenticationEntryPoint(AuthenticationEntryPointauthenticationEntryPoint) {
super.setAuthenticationEntryPoint(null);
this.authenticationEntryPoint=authenticationEntryPoint;
    }
@OverrideprotectedAuthenticationManagergetAuthenticationManager() {
returnconfigurer.and().getSharedObject(AuthenticationManager.class);
    }
@OverridepublicvoidafterPropertiesSet() {
setAuthenticationFailureHandler((request, response, e) ->authenticationEntryPoint.commence(request, response, e));
setAuthenticationSuccessHandler((request, response, authentication) -> {
        });
    }
}


在认证服务器注入异常处理逻辑,自定义异常返回结果。(代码位于 AuthorizationServerConfig


@BeanpublicAuthenticationEntryPointauthenticationEntryPoint() {
return (request, response, e) -> {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
ResultData<String>resultData=ResultData.fail(ReturnCode.CLIENT_AUTHENTICATION_FAILED.getCode(), ReturnCode.CLIENT_AUTHENTICATION_FAILED.getMessage());
WebUtils.writeJson(response,resultData);
    };
}


修改认证服务器配置,注入自定义过滤器


@Overridepublicvoidconfigure(AuthorizationServerSecurityConfigurersecurity) throwsException {
CustomClientCredentialsTokenEndpointFilterendpointFilter=newCustomClientCredentialsTokenEndpointFilter(security);
endpointFilter.afterPropertiesSet();
endpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint());
security.addTokenEndpointAuthenticationFilter(endpointFilter);
security   .authenticationEntryPoint(authenticationEntryPoint())
/* .allowFormAuthenticationForClients()*///如果使用表单认证则需要加上   .tokenKeyAccess("permitAll()")
   .checkTokenAccess("isAuthenticated()");
}


此时需要删除 allowFormAuthenticationForClients()配置,否则自定义的过滤器不生效,至于为什么不生效大家看看源码就知道了。


测试


  • 授权模式错误


5.png


  • 账号密码错误


6.png


  • 客户端错误


7.png


以上,希望对你有所帮助!

目录
相关文章
|
4月前
|
消息中间件 Java 开发工具
Spring Cloud【Finchley】实战-06使用/actuator/bus-refresh端点手动刷新配置 + 使用Spring Cloud Bus自动更新配置
Spring Cloud【Finchley】实战-06使用/actuator/bus-refresh端点手动刷新配置 + 使用Spring Cloud Bus自动更新配置
181 0
|
3月前
|
监控 Java Sentinel
使用Sentinel进行服务调用的熔断和限流管理(SpringCloud2023实战)
Sentinel是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。
116 3
|
3月前
|
开发框架 移动开发 JavaScript
SpringCloud微服务实战——搭建企业级开发框架(四十七):【移动开发】整合uni-app搭建移动端快速开发框架-添加Axios并实现登录功能
在uni-app中,使用axios实现网络请求和登录功能涉及以下几个关键步骤: 1. **安装axios和axios-auth-refresh**: 在项目的`package.json`中添加axios和axios-auth-refresh依赖,可以通过HBuilderX的终端窗口运行`yarn add axios axios-auth-refresh`命令来安装。 2. **配置自定义常量**: 创建`project.config.js`文件,配置全局常量,如API基础URL、TenantId、APP_CLIENT_ID和APP_CLIENT_SECRET等。
204 60
|
3月前
|
JSON Java 程序员
马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day1最快 最全(2)
马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day1最快 最全(2)
41 3
|
3月前
|
程序员 测试技术 Docker
黑马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day3 全网最全
黑马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day3 全网最全(1)
309 1
|
3月前
|
SQL Java 程序员
马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day1最快 最全(1)
马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day1最快 最全(1)
181 1
|
3月前
|
JSON Java Spring
实战SpringCloud响应式微服务系列教程(第八章)构建响应式RESTful服务
实战SpringCloud响应式微服务系列教程(第八章)构建响应式RESTful服务
|
3月前
|
关系型数据库 MySQL Shell
黑马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day2 全网最快最全(下)
黑马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day2 全网最快最全(下)
185 0
|
3月前
|
Java 程序员 Docker
黑马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day2 全网最快最全(上)
黑马程序员2024最新SpringCloud微服务开发与实战 个人学习心得、踩坑、与bug记录Day2 全网最快最全(上)
149 0
|
4月前
|
开发框架 移动开发 JavaScript
SpringCloud微服务实战——搭建企业级开发框架(四十六):【移动开发】整合uni-app搭建移动端快速开发框架-环境搭建
正如优秀的软件设计一样,uni-app把一些移动端常用的功能做成了独立的服务或者插件,我们在使用的时候只需要选择使用即可。但是在使用这些服务或者插件时一定要区分其提供的各种服务和插件的使用场景,例如其提供的【uni-starter快速开发项目模版】几乎集成了移动端所需的所有基础功能,使用非常方便,但是其许可协议只允许对接其uniCloud的JS开发服务端,不允许对接自己的php、java等其他后台系统。
278 61

热门文章

最新文章