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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值