服务提供方 Authorization Server。
资源持有者 Resource Server。
客户端 Client。
下面重点介绍下spring cloud 使用oauth2问题,内容如下所示:
1、spring boot 集成oauth2,带了token却访问时各种禁止访问,追踪代码过滤器发现变为匿名用户导致无法访问授权资源,添加过滤器各种都没效果,甚至添加了过滤器登录都登录不了了,
添加的依赖为
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!--oauth2依赖--> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.3.RELEASE</version> </dependency>
将其直接改为spring-cloud-starter-oauth2 依赖,问题解决
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> <version>2.2.5.RELEASE</version> </dependency>
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看,同一个类被不同的classloader加载了,导致无法匹配,
通过查资料等最终确定问题是 spring-boot-devtools 这个依赖引起的
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency>
问题分析
分析出ClassLoader不同导致的类型转换异常,Spring的dev-tools为了实现重新装载class自己实现了一个类加载器,来加载项目中会改变的类,方便重启时将新改动的内容更新进来,其实其中官方文档中是有做说明的:
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
做猪小侠源码的代理,提供一站式服务
如果你不懂得搭建网站或者服务器,小程序,源码之类的怎么办? 第一通过本站学习各种互联网的技术 第二就是联系客服,我帮帮你搭建(当然要收取部分的费用) 第三成为我们的代理,我们提供整套的服务。