spring cloud 使用oauth2 問題匯總

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

到此這篇關於spring cloud 使用oauth2 問題匯總的文章就介紹到這瞭,更多相關spring cloud 使用oauth2內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: