OAuth2 核心角色与协议简介
OAuth2 是一项标准化的授权协议规范。
在认证与授权的交互流程中,主要涉及三个核心角色。
服务提供方即 Authorization Server(授权服务器)。 资源持有者即 Resource Server(资源服务器)。 发起请求的客户端即 Client。
接下来重点梳理 Spring Cloud 集成 OAuth2 过程中遇到的典型问题及对应解决方案。
1. Spring Boot 集成 OAuth2 后,即使携带了有效的 Token,访问接口时仍频繁出现禁止访问的错误。追踪代码过滤器发现请求被识别为匿名用户,从而导致无法获取授权资源。尝试添加各种过滤器均未见效,甚至导致登录功能失效。
原项目中引入的依赖配置如下:
org.springframework.boot
spring-boot-starter-security
org.springframework.security.oauth
spring-security-oauth2
2.3.3.RELEASE
将该依赖直接替换为 spring-cloud-starter-oauth2 后,上述问题得以解决。
org.springframework.cloud
spring-cloud-starter-oauth2
2.2.5.RELEASE
2. 在 Spring Cloud OAuth2 中使用自定义的 UserDetails 实现类后,通过以下代码
authentication.getPrincipal() instanceof OpenUserDetails
进行用户信息获取时,经常抛出类型匹配失败的异常。
当使用强制类型转换 (OpenUserDetails) authentication.getPrincipal() 时,直接报错。
具体错误信息为:java.lang.ClassCastException: com.kou.auth.OpenUserDetails cannot be cast to com.kou.auth.OpenUserDetails。
通过检查 ClassLoader 发现,同一个类被不同的类加载器加载,导致运行时类型不匹配。
经过查阅相关资料,最终确定该问题是由 spring-boot-devtools 依赖引起的。
org.springframework.boot
spring-boot-devtools
runtime
true
问题分析 由于 ClassLoader 不同导致了类型转换异常。Spring 的 dev-tools 为了实现类的热重载,自行实现了一个特殊的类加载器,用于加载项目中可能发生变更的类,以便在重启时快速更新改动内容。官方文档对此有明确说明:
By default, any open project in your IDE will be loaded using the “restart” classloader, and any regular .jar file will be loaded using the “base” classloader. If you work on a multi-module project, and not each module is imported into your IDE, you may need to customize things. To do this you can create a META-INF/spring-devtools.properties file. The spring-devtools.properties file can contain restart.exclude. and restart.include. prefixed properties. The include elements are items that should be pulled up into the “restart” classloader, and the exclude elements are items that should be pushed down into the “base” classloader. The value of the property is a regex pattern that will be applied to the classpath.
处理方法一:直接删除该依赖。
或者采用方法二:
在 resources 目录下创建 META-INF 文件夹,然后创建 spring-devtools.properties 文件,并在文件中添加类似如下配置:
restart.exclude.companycommonlibs=/mycorp-common-[\w-]+.jar
restart.include.projectcommon=/mycorp-myproj-[\w-]+.jar
至此,关于 Spring Cloud 使用 OAuth2 常见问题的汇总介绍完毕。如需了解更多相关内容,请搜索本站历史文章或继续浏览后续推荐内容,感谢您的支持!