Spring Security整合Oauth2實現(xiàn)流程詳解
一、創(chuàng)建項目并導入依賴
<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的認證模式,用于前后端分離登陸
第三方登陸一般是授權(quán)碼模式
二、相關(guān)配置和代碼
注:授權(quán)服務器和資源服務器一般是分開來的,我這里就不分開了
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)創(chuàng)建授權(quán)服務
2.2.1)實現(xiàn)AuthorizationServiceConfigurerAdapter
@Configuration表示這個一個配置類
@EnableAuthorizationServer表示開啟授權(quán)服務
2.2.2)注入AuthenticationManager、RedisConnectionFactory、UserDetailsService
AuthenticationManager表示支持password認證模式
RedisConnectionFactory登陸成功后的token需要存在redis里面,因為redis里面有過期機制
UserDetailsService里面存放著用戶信息
2.2.3)重寫方法
2.3)創(chuàng)建資源服務
2.3.1)實現(xiàn)ResourceServerConfigurerAdapter
@configuration表示這是一個配置類
@enbaleResourceServer表示開啟資源服務
2.3.2)重寫方法
2.4)創(chuàng)建Security配置類
2.4.1)實現(xiàn)WebSecurityConfigurerAdapter
2.4.2)將授權(quán)服務需要的兩個bean,提供給它
@Bean表示告訴方法,產(chǎn)生一個Bean對象,然后這個Bean對象交給Spring管理。產(chǎn)生這個Bean對象的方法Spring只會調(diào)用一次,隨后這個Spring將會將這個Bean對象放在自己的IOC容器中。
@Bean和@Component作用一樣都是將bean注冊到spring容器中去
2.4.3)重寫方法
2.5)創(chuàng)建Controller
三、測試&效果
3.1)獲取訪問資源服務的token
3.2)訪問資源服務
3.3)刷新token
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章: