spring cloud 使用oauth2

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring cloud 使用oauth2

风行傲天   2022-09-29 我要评论

OAth2是一个标准的授权协议。

在认证与授权的过程中,主要包含以下3种角色。

服务提供方 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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们