Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理

简介: Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理

本文完整代码下载点击

微信图片_20230709224442.gif

一. 前言

相信了解过我或者看过我之前的系列文章应该多少知道点我写这些文章包括创建 有来商城youlai-mall 这个项目的目的,想给那些真的想提升自己或者迷茫的人(包括自己–一个工作6年觉得一无是处的菜鸟)提供一块上升的基石。项目是真的从无到有(往期文章佐证),且使用当前主流的开发模式(微服务+前后端分离),最新主流的技术栈(Spring Boot+ Spring Cloud +Spring Cloud Alibaba + Vue),最流行的统一安全认证授权(OAuth2+JWT),好了玩笑开完了大家别当真,总之有兴趣一起的小伙伴欢迎加入~


接下来说下这篇文章的原因,之前我是没想过应用到项目中的OAuth2+JWT这套组合拳这么受大家关注,期间一直有童鞋问怎么自定义Spring Security OAuth2的异常处理、JWT怎么续期、JWT退出等场景下如何失效等问题,所以最近有点时间想把这套统一认证授权完善掉,本篇就以如何自定义Spring Security OAuth2异常处理展开。


往期文章链接:


后端


Spring Cloud实战 | 第一篇:Windows搭建Nacos服务

Spring Cloud实战 | 第二篇:Spring Cloud整合Nacos实现注册中心

Spring Cloud实战 | 第三篇:Spring Cloud整合Nacos实现配置中心

Spring Cloud实战 | 第四篇:Spring Cloud整合Gateway实现API网关

Spring Cloud实战 | 第五篇:Spring Cloud整合OpenFeign实现微服务之间的调用

Spring Cloud实战 | 第六篇:Spring Cloud Gateway+Spring Security OAuth2+JWT实现微服务统一认证授权

Spring Cloud实战 | 最七篇:Spring Cloud Gateway+Spring Security OAuth2集成统一认证授权平台下实现注销使JWT失效方案

Spring Cloud实战 | 最八篇:Spring Cloud +Spring Security OAuth2+ Vue前后端分离模式下无感知刷新实现JWT续期

Spring Cloud实战 | 最九篇:Spring Security OAuth2认证服务器统一认证自定义异常处理

管理前端


vue-element-admin实战 | 第一篇: 移除mock接入后台,搭建有来商城youlai-mall前后端分离管理平台

vue-element-admin实战 | 第二篇: 最小改动接入后台实现根据权限动态加载菜单

微信小程序


vue+uniapp商城实战 | 第一篇:【有来小店】微信小程序快速开发接入Spring Cloud OAuth2认证中心完成授权登录

二. 自定义异常实现代码

直接需要答案的本节走起,添加和修改三个文件即可,异常分析,点击下载完整工程代码


1. 在youlai-auth认证服务器模块添加全局异常处理器AuthExceptionHandler


package com.youlai.auth.exception;


import com.youlai.common.core.result.Result;

import com.youlai.common.core.result.ResultCode;

import lombok.extern.slf4j.Slf4j;

import org.springframework.security.authentication.InternalAuthenticationServiceException;

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice

@Slf4j

public class AuthExceptionHandler {

   /**

    * 用户名和密码错误

    *

    * @param e

    * @return

    */

   @ExceptionHandler(InvalidGrantException.class)

   public Result handleInvalidGrantException(InvalidGrantException e) {

       return Result.custom(ResultCode.USERNAME_OR_PASSWORD_ERROR);

   }

   /**

    * 账户异常(禁用、锁定、过期)

    *

    * @param e

    * @return

    */

   @ExceptionHandler({InternalAuthenticationServiceException.class})

   public Result handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {

       return Result.error(e.getMessage());

   }

}


2. 重写ClientCredentialsTokenEndpointFilter实现客户端自定义异常处理


package com.youlai.auth.filter;

import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;

import org.springframework.security.web.AuthenticationEntryPoint;

/**

* 重写filter实现客户端自定义异常处理

*/

public class CustomClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter {

   private AuthorizationServerSecurityConfigurer configurer;

   private AuthenticationEntryPoint authenticationEntryPoint;

   public CustomClientCredentialsTokenEndpointFilter(AuthorizationServerSecurityConfigurer configurer) {

       this.configurer = configurer;

   }

   @Override

   public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {

       super.setAuthenticationEntryPoint(null);

       this.authenticationEntryPoint = authenticationEntryPoint;

   }

   @Override

   protected AuthenticationManager getAuthenticationManager() {

       return configurer.and().getSharedObject(AuthenticationManager.class);

   }

   @Override

   public void afterPropertiesSet() {

       setAuthenticationFailureHandler((request, response, e) -> authenticationEntryPoint.commence(request, response, e));

       setAuthenticationSuccessHandler((request, response, authentication) -> {

       });

   }

}



3. AuthorizationServerConfig认证服务器配置修改


/**

* 授权服务配置

*/

@Configuration

@EnableAuthorizationServer

@AllArgsConstructor

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


   ......


   @Override

   public void configure(AuthorizationServerSecurityConfigurer security) {

       /*security.allowFormAuthenticationForClients();*/

       CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(security);

       endpointFilter.afterPropertiesSet();

       endpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint());

       security.addTokenEndpointAuthenticationFilter(endpointFilter);

       security.authenticationEntryPoint(authenticationEntryPoint())

               .tokenKeyAccess("isAuthenticated()")

               .checkTokenAccess("permitAll()");

   }

   @Bean

   public AuthenticationEntryPoint authenticationEntryPoint() {

       return (request, response, e) -> {

           response.setStatus(HttpStatus.HTTP_OK);

           response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);

           response.setHeader("Access-Control-Allow-Origin", "*");

           response.setHeader("Cache-Control", "no-cache");

           Result result = Result.custom(ResultCode.CLIENT_AUTHENTICATION_FAILED);

           response.getWriter().print(JSONUtil.toJsonStr(result));

           response.getWriter().flush();

       };

   }

   ......

}


三. 异常处理分析

其实你搜一下有关Spring Security OAuth2如何自定义异常处理,网上会很多差不多解决方案提供参考,但是照搬过来试用,一点效果没有?!咋回事么?其实不能武断的说人家方案不行,最多的可能是Spring Security OAuth2版本不一致,本篇项目使用的是2.3.4版本,目前截止写这篇文章最新一版的是2020.5.28发布的2.5.0版本,后续项目会升级,如果有差异我会修改本篇文章,总之给大家提供一个解决思路,可行不可行我是不希望大家不能在我里浪费时间。


好了正文开始了~ Spring Security OAuth2认证服务器异常目前我知道的有3类:


用户名或密码错误

账户状态异常

客户端认证异常

有知道其他的欢迎留言补充~,以下就这3类异常逐一分析


在异常处理之前先看下UserDetailsServiceImpl#loadUserByUsername方法抛出的异常信息,如下图:


微信图片_20230709224513.png


1. 用户名或密码错误

异常分析

org.springframework.security.oauth2.common.exceptions.InvalidGrantException: 用户名或密码错误

1微信图片_20230709224524.png



通过异常堆栈信息定位到最终抛出异常的方法是ResourceOwnerPasswordTokenGranter#getOAuth2Authentication,异常类型是InvalidGrantException,其实到这个异常类型中间经过几道转换UsernameNotFoundException->BadCredentialsException->InvalidGrantException


处理方法

添加全局异常处理器捕获(定位标识:AuthExceptionHandler)



/**

* 用户名和密码异常

*

* @param e

* @return

*/

@ExceptionHandler(InvalidGrantException.class)

public Result handleInvalidGrantException(InvalidGrantException e) {

   return Result.error(ResultCode.USERNAME_OR_PASSWORD_ERROR);

}


结果验证

验证成功,已按照自定义异常格式返回

微信图片_20230709224527.png



2. 账户状态异常

异常分析

首先我们需要把数据库youlai的表sys_user的字段status设置为0,表示不可用状态,然后输入正确的用户名和密码,看看跑出来的原生异常信息,可惜的是这个异常没有打印堆栈信息,不过没关系,我们断点调试下,最终定位到ProviderManager#authenticate方法抛出的异常,异常类型是InternalAuthenticationServiceException。

微信图片_20230709224546.png



处理方法

添加全局异常处理器捕获(定位标识:AuthExceptionHandler)


/**

* 账户异常(禁用、锁定、过期)

*

* @param e

* @return

*/

@ExceptionHandler({InternalAuthenticationServiceException.class})

public Result handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {

   return Result.error(e.getMessage());

}


结果验证

验证成功,已按照自定义异常格式返回

微信图片_20230709224550.png



3. 客户端认证异常

异常分析

之前两种异常方式都可以通过全局异常处理器捕获,且@RestControllerAdvice只能捕获Controller的异常。


客户端认证的异常则是发生在过滤器filter上,此时还没进入DispatcherServlet请求处理流程,便无法通过全局异常处理器捕获。


先看下客户端认证异常出现的位置,首先把客户端ID改成错的。


微信图片_20230709224610.png


然后执行“登录”操作,返回错误信息如下:


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

1

一眼望去,这显然不是我们想要的格式。


那怎么做才能捕获这个异常转换成自定义数据格式返回呢?显然全局异常处理器无法实现,那必须转换下思路了。


首先客户端的认证是交由ClientCredentialsTokenEndpointFilter来完成的,其中有后置添加失败处理方法,最后把异常交给OAuth2AuthenticationEntryPoint这个所谓认证入口处理。


微信图片_20230709224647.png


认证入口OAuth2AuthenticationEntryPoint#commence方法中转给父类AbstractOAuth2SecurityExceptionHandler#doHandle方法。


微信图片_20230709224650.png


最后异常定格在AbstractOAuth2SecurityExceptionHandler#doHandle方法上,如下图:

微信图片_20230709224708.png微信图片_20230709224710.png



其中this.enhanceResponse是调用OAuth2AuthenticationEntryPoint#enhanceResponse方法得到响应结果数据。


处理方法

上面我们得知客户端的认证失败异常是过滤器ClientCredentialsTokenEndpointFilter转交给OAuth2AuthenticationEntryPoint得到响应结果的,既然这样我们就可以重写ClientCredentialsTokenEndpointFilter然后使用自定义的AuthenticationEntryPoint替换原生的OAuth2AuthenticationEntryPoint,在自定义AuthenticationEntryPoint处理得到我们想要的异常数据。


自定义AuthenticationEntryPoint设置异常响应数据格式


微信图片_20230709224725.png


重写ClientCredentialsTokenEndpointFilter替换AuthenticationEntryPoint

微信图片_20230709224728.png



认证服务器配置添加自定义过滤器

微信图片_20230709224743.png



结果验证

验证成功,已按照自定义异常格式返回


微信图片_20230709224745.png


四. 总结

至此,认证服务器的自定义异常处理已全部处理完毕,资源服务器异常处理说明在这篇文章 Spring Cloud实战 | 第六篇:Spring Cloud Gateway+Spring Security OAuth2+JWT实现微服务统一认证授权,这就宣告 youlai-mall 的统一认证授权模块基本达到完善的一个标准, 后面继续回到业务功能的开发,所以觉得对你有帮助的给个关注(持续更新)或者给个star,灰常感谢! 最重要的如果你真的对这个项目有兴趣想一起开发学习的像文章开始说的那样请联系我哈~


相关文章
|
2天前
|
安全 Java 测试技术
Spring Boot集成支付宝支付:概念与实战
【4月更文挑战第29天】在电子商务和在线业务应用中,集成有效且安全的支付解决方案是至关重要的。支付宝作为中国领先的支付服务提供商,其支付功能的集成可以显著提升用户体验。本篇博客将详细介绍如何在Spring Boot应用中集成支付宝支付功能,并提供一个实战示例。
16 2
|
2天前
|
监控 Java 测试技术
Spring Boot与事务钩子函数:概念与实战
【4月更文挑战第29天】在复杂的业务逻辑中,事务管理是确保数据一致性和完整性的关键。Spring Boot提供了强大的事务管理机制,其中事务钩子函数(Transaction Hooks)允许开发者在事务的不同阶段插入自定义逻辑。本篇博客将详细探讨事务钩子函数的概念及其在Spring Boot中的应用。
11 1
|
2天前
|
Java 关系型数据库 数据库
Spring Boot多数据源及事务管理:概念与实战
【4月更文挑战第29天】在复杂的企业级应用中,经常需要访问和管理多个数据源。Spring Boot通过灵活的配置和强大的框架支持,可以轻松实现多数据源的整合及事务管理。本篇博客将探讨如何在Spring Boot中配置多数据源,并详细介绍事务管理的策略和实践。
18 3
|
2天前
|
前端开发 Java 数据安全/隐私保护
Spring Boot使用拦截器:概念与实战
【4月更文挑战第29天】拦截器(Interceptors)在Spring Boot应用中常用于在请求处理的前后执行特定的代码,如日志记录、认证校验、权限控制等。本篇博客将详细介绍Spring Boot中拦截器的概念及其实战应用,帮助开发者理解和利用拦截器来增强应用的功能。
10 0
|
2天前
|
JSON Java 数据处理
Spring Boot与Jsonson对象:灵活的JSON操作实战
【4月更文挑战第28天】在现代Web应用开发中,JSON数据格式的处理至关重要。假设 "Jsonson" 代表一个类似于Jackson的库,这样的工具在Spring Boot中用于处理JSON。本篇博客将介绍Spring Boot中处理JSON数据的基本概念,并通过实际例子展示如何使用类似Jackson的工具进行数据处理。
12 0
|
2天前
|
监控 Java Sentinel
Spring Cloud Sentinel:概念与实战应用
【4月更文挑战第28天】在分布式微服务架构中,确保系统的稳定性和可靠性至关重要。Spring Cloud Sentinel 为微服务提供流量控制、熔断降级和系统负载保护,有效预防服务雪崩。本篇博客深入探讨 Spring Cloud Sentinel 的核心概念,并通过实际案例展示其在项目中的应用。
11 0
|
3天前
|
Cloud Native Java Nacos
Spring Cloud Nacos:概念与实战应用
【4月更文挑战第28天】Spring Cloud Nacos 是一个基于 Spring Cloud 构建的服务发现和配置管理工具,适用于微服务架构。Nacos 提供了动态服务发现、服务配置、服务元数据及流量管理等功能,帮助开发者构建云原生应用。
9 0
|
2月前
|
Java Nacos Sentinel
Spring Cloud Alibaba 面试题及答案整理,最新面试题
Spring Cloud Alibaba 面试题及答案整理,最新面试题
216 0
|
2月前
|
SpringCloudAlibaba Java 持续交付
【构建一套Spring Cloud项目的大概步骤】&【Springcloud Alibaba微服务分布式架构学习资料】
【构建一套Spring Cloud项目的大概步骤】&【Springcloud Alibaba微服务分布式架构学习资料】
170 0
|
2月前
|
SpringCloudAlibaba Java 网络架构
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关
108 0