Spring Security整合Oauth2實現流程詳解
一、創(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的認證模式,用于前后端分離登陸
第三方登陸一般是授權碼模式
二、相關配置和代碼
注:授權服務器和資源服務器一般是分開來的,我這里就不分開了
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)建授權服務
2.2.1)實現AuthorizationServiceConfigurerAdapter

@Configuration表示這個一個配置類
@EnableAuthorizationServer表示開啟授權服務
2.2.2)注入AuthenticationManager、RedisConnectionFactory、UserDetailsService

AuthenticationManager表示支持password認證模式
RedisConnectionFactory登陸成功后的token需要存在redis里面,因為redis里面有過期機制
UserDetailsService里面存放著用戶信息
2.2.3)重寫方法


2.3)創(chuàng)建資源服務
2.3.1)實現ResourceServerConfigurerAdapter

@configuration表示這是一個配置類
@enbaleResourceServer表示開啟資源服務
2.3.2)重寫方法

2.4)創(chuàng)建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)創(chuàng)建Controller

三、測試&效果
3.1)獲取訪問資源服務的token

3.2)訪問資源服務

3.3)刷新token

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Springsecurity Oauth2如何設置token的過期時間
- 詳解使用Spring Security OAuth 實現OAuth 2.0 授權
- Spring Security OAuth2實現使用JWT的示例代碼
- 基于Spring Security的Oauth2授權實現方法
- SpringSecurityOAuth2 如何自定義token信息
- SpringSecurity OAuth2單點登錄和登出的實現
- SpringBoot的Security和OAuth2的使用示例小結
- Spring Security OAuth過期的解決方法
- Spring Security OAuth2認證授權示例詳解
- Spring Security OAuth2.0登出的實現
相關文章
Netty分布式NioEventLoop任務隊列執(zhí)行源碼分析
這篇文章主要為大家介紹了Netty分布式NioEventLoop任務隊列執(zhí)行源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-03-03
eclipse下整合springboot和mybatis的方法步驟
這篇文章主要介紹了eclipse下整合springboot和mybatis的方法步驟,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03

