SpringSecurity整合Oauth2


一、創建項目並導入依賴

   

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.security.oauth</groupId>

<artifactId>spring-security-oauth2</artifactId>

<version>2.3.6.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

   

   

注:這里的oauth2不是springboot那個,這是springsecurity。

Oauth2一共有四種認證模式是

本篇是password的認證模式,用於前后端分離登陸

第三方登陸一般是授權碼模式

   

   

二、相關配置和代碼

   

:授權服務器和資源服務器一般是分開來的,我這里就不分開了

   

2.1)application.properties

   

spring.redis.host=192.168.21.135

spring.redis.port=6379

spring.redis.database=0

spring.redis.password=520hufei520

   

2.2)創建授權服務

   

2.2.1)實現AuthorizationServiceConfigurerAdapter

   

   

@Configuration表示這個一個配置類

@EnableAuthorizationServer表示開啟授權服務

   

2.2.2)注入AuthenticationManager、RedisConnectionFactory、UserDetailsService

   

AuthenticationManager表示支持password認證模式

   

RedisConnectionFactory登陸成功后的token需要存在redis里面,因為redis里面有過期機制

   

UserDetailsService里面存放着用戶信息

   

2.2.3)重寫方法

   

   

   

2.3)創建資源服務

   

2.3.1)實現ResourceServerConfigurerAdapter

   

   

@configuration表示這是一個配置類

@enbaleResourceServer表示開啟資源服務

   

2.3.2)重寫方法

   

2.4)創建Security配置類

   

2.4.1)實現WebSecurityConfigurerAdapter

   

   

2.4.2)將授權服務需要的兩個bean,提供給它

   

   

   

@Bean表示告訴方法,產生一個Bean對象,然后這個Bean對象交給Spring管理。產生這個Bean對象的方法Spring只會調用一次,隨后這個Spring將會將這個Bean對象放在自己的IOC容器中。

@Bean和@Component作用一樣都是將bean注冊到spring容器中去

   

2.4.3)重寫方法

   

2.5)創建Controller

   

   

   

三、測試&效果圖

   

3.1)獲取訪問資源服務的token

   

   

   

3.2)訪問資源服務

   

   

   

3.3)刷新token

   

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM