springboot 整合oauth2

1、@EnableOAuth2Client:客戶端,提供OAuth2RestTemplate,用于客戶端訪問資源服務。?
簡要步驟:客戶端訪問資源->客戶端發現沒有資源訪問token->客戶端根據授權類型生成跳轉url->瀏覽器 302 到認證授權服務進行認證、授權。
2、@EnableOAuth2Sso:應用系統,使用遠端認證授權服務,替換應用自身的用戶登錄鑒權security邏輯,實現單點登錄功能。?
簡要步驟:訪問應用系統資源-> 應用系統發現未登錄-> 302 跳轉到登錄頁面(登錄頁面地址已經與獲取token邏輯自動關聯)-> 應用系統發現符合獲取token條件,根據授權類型拼裝url->302 跳轉到認證授權地址(認證授權服務提供)進行認證、授權。
3、@EnableAuthorizationServer:認證授權服務,提供用于獲取token,解析token相關功能,實現認證、授權功能。
具體見 Spring Security 文章目錄中的 Spring Cloud OAuth2 五種授權方式介紹。
4、@EnableResourceServer:資源服務,提供基于token的資源訪問功能。

<--認證服務器配置-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-security</artifactId>
</dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {@Autowiredprivate DataSource dataSource;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate RedisConnectionFactory redisConnectionFactory;@Autowiredprivate CodeStoreService codeStoreService;@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {security.allowFormAuthenticationForClients().tokenKeyAccess("isAuthenticated()").checkTokenAccess("isAuthenticated()");}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.jdbc(dataSource).passwordEncoder(passwordEncoder);}@Beanpublic JwtTokenStore jwtTokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());}@Beanpublic RedisTokenStore redisTokenStore() {return new RedisTokenStore(redisConnectionFactory);}@Beanpublic AuthorizationServerTokenServices authorizationServerTokenServices() {DefaultTokenServices defaultTokenServices = new DefaultTokenServices();defaultTokenServices.setTokenStore(redisTokenStore());defaultTokenServices.setSupportRefreshToken(true);defaultTokenServices.setRefreshTokenValiditySeconds(30 * 60 * 1000);defaultTokenServices.setAccessTokenValiditySeconds(30 * 69 * 1000);return defaultTokenServices;}@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter() {ClassPathResource resource = new ClassPathResource("user.jks");KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, "123456".toCharArray());JwtAccessTokenConverter jwtTokenConverter = new JwtAccessTokenConverter();jwtTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("xm"));return jwtTokenConverter;}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.allowedTokenEndpointRequestMethods(HttpMethod.POST);endpoints.authenticationManager(authenticationManager);//endpoints.accessTokenConverter(jwtAccessTokenConverter());endpoints.tokenServices(authorizationServerTokenServices());endpoints.authorizationCodeServices(codeStoreService);}
}

spring security 的配置文件

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate CustomUserDetailsService userDetailsService;@Autowiredprivate SuccessAuthentication successAuthentication;@Autowiredprivate FailureAuthentication failureAuthentication;@Autowiredprivate UnauthorizedEntryPoint unauthorizedEntryPoint;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);}@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overridepublic void configure(WebSecurity web) {web.ignoring().mvcMatchers("/assets/**", "/css/**", "/images/**");}@Overrideprotected void configure(HttpSecurity http) throws Exception {/*http.csrf().disable();http.authorizeRequests().antMatchers( "/oauth/token", "/check/token").permitAll();http.authorizeRequests().antMatchers("/success").hasRole("USER").antMatchers("/success").hasRole("ADMIN").antMatchers("/user/r1").hasRole("USER").antMatchers("/user/r2").hasRole("ADMIN").antMatchers("/user/p1").hasAuthority("p1").antMatchers("/user/p2").hasAuthority("p2").anyRequest().authenticated().and().formLogin().loginPage("/login").successForwardUrl("/success").and().exceptionHandling().accessDeniedHandler(new CustomAccessDecisionHandler()).and().httpBasic();*/http.csrf().disable();http.formLogin().loginPage("/login")//.successHandler(successAuthentication)//.failureHandler(failureAuthentication).and().authorizeRequests().antMatchers("/login").permitAll().anyRequest().authenticated().and()/*.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint).and()*/.rememberMe(remember ->remember.rememberMeParameter("remember-me").rememberMeCookieName("remember-me").tokenValiditySeconds(30 * 1000).userDetailsService(userDetailsService));}
}

資源服務器使用spring-boot-starter-oauth2-client

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.security.oauth.boot</groupId><artifactId>spring-security-oauth2-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-client</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-resource-server</artifactId></dependency><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId><version>3.0.4.RELEASE</version>
</dependency>
spring.security.oauth2.client.registration.user.provider=user
spring.security.oauth2.client.registration.user.client-id=user-service
spring.security.oauth2.client.registration.user.client-secret=root
spring.security.oauth2.client.registration.user.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.user.redirect-uri=http://localhost:9091/login
spring.security.oauth2.client.registration.user.scope=all
spring.security.oauth2.client.provider.user.authorization-uri=http://localhost:9091/oauth/authorize
spring.security.oauth2.client.provider.user.token-uri=http://localhost:9091/oauth/token
spring.security.oauth2.client.provider.user.user-info-uri=http://localhost:9091/oauth2/userinfo
spring.security.oauth2.client.provider.user.user-name-attribute=sub
spring.security.oauth2.client.provider.user.jwk-set-uri=http://localhost:9091/oauth/token_key
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:9091/oauth/token_key
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated();http.oauth2ResourceServer(oauth2->oauth2.jwt());// 改成oauth2Login 就是oauth 登錄}
}

參考資料

https://www.cnblogs.com/atwood-pan/p/17787904.html

OAuth2 - @EnableResourceServer vs @EnableOAuth2Sso | Baeldung

Spring-Security-OAuth2-Client | zyc的博客

spring oauth2實現單點登錄,Vue+spring boot+oauth2前后端分離 - 簡書

(二)、Spring Security OAuth2 四個常用注解說明_oauth2clientcontext是什么-CSDN博客

https://www.cnblogs.com/atwood-pan/p/17787904.html

springsecurity oauth2實現前后端分離項目的SSO技術點總結_spring outh2 前后端分離-CSDN博客

【Spring Security OAuth2 Client】基本介紹以及定制開發_spring-boot-starter-oauth2-client-CSDN博客

springboot整合Oauth2_spring-boot-starter-oauth2-client-CSDN博客

https://www.cnblogs.com/simpleito/p/15786122.html

自定義grant_type 以及第三方登錄。

總之,這個東西比較復雜,暫且放過
?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/718054.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/718054.shtml
英文地址,請注明出處:http://en.pswp.cn/news/718054.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Dockerfile構建過程詳解

Dockerfile介紹 docker是用來構建docker鏡像的文件&#xff01;命令參數腳本&#xff01; 構建步驟&#xff1a; 1、編寫一個dockerfile文件 2、docker build構建成為一個鏡像 3、docker run 運行鏡像 …

PDF轉Excel的未來:人工智能技術如何提升轉換效率和準確性

隨著信息技術的快速發展&#xff0c;PDF和Excel作為兩種重要的文件格式&#xff0c;在日常生活和工作中扮演著至關重要的角色。PDF以其獨特的跨平臺閱讀特性&#xff0c;成為了文件分享和傳輸的首選格式&#xff1b;而Excel則以其強大的數據處理能力&#xff0c;成為了數據分析…

【二分查找】【C++算法】378. 有序矩陣中第 K 小的元素

作者推薦 視頻算法專題 本文涉及的基礎知識點 二分查找算法合集 LeetCode378. 有序矩陣中第 K 小的元素 給你一個 n x n 矩陣 matrix &#xff0c;其中每行和每列元素均按升序排序&#xff0c;找到矩陣中第 k 小的元素。 請注意&#xff0c;它是 排序后 的第 k 小元素&…

機器人持續學習基準LIBERO系列10——文件結構

0.前置 機器人持續學習基準LIBERO系列1——基本介紹與安裝測試機器人持續學習基準LIBERO系列2——路徑與基準基本信息機器人持續學習基準LIBERO系列3——相機畫面可視化及單步移動更新機器人持續學習基準LIBERO系列4——robosuite最基本demo機器人持續學習基準LIBERO系列5——…

力扣日記3.3-【回溯算法篇】332. 重新安排行程

力扣日記&#xff1a;【回溯算法篇】332. 重新安排行程 日期&#xff1a;2023.3.3 參考&#xff1a;代碼隨想錄、力扣 ps&#xff1a;因為是困難題&#xff0c;望而卻步了一星期。。。T^T 332. 重新安排行程 題目描述 難度&#xff1a;困難 給你一份航線列表 tickets &#xf…

牛客小白月賽86

A-水鹽平衡_牛客小白月賽86 (nowcoder.com) #include<bits/stdc.h> #define endl \n #define int long long using namespace std; int a,b,c,d; void solve() {cin>>a>>b>>c>>d;if((double)a/b>(double)c/d) cout<<S<<endl;els…

關于脈沖負載應用中電阻器,您需要了解的 11 件事?

不幸的是&#xff0c;電阻器在脈沖負載下可能會失效。當脈沖功率耗散到器件的電阻元件時&#xff0c;它會產生熱量并增加電阻器的溫度。過熱會損壞電阻元件&#xff0c;導致電阻變化甚至設備開路。為了避免在設計中出現這種情況&#xff0c;以下是您在選擇元件時應了解的有關電…

excel統計分析——拉丁方設計

參考資料&#xff1a;生物統計學 拉丁方設計也是隨機區組設計&#xff0c;是對隨機區組設計的一種改進。它在行的方向和列的方向都可以看成區組&#xff0c;因此能實現雙向誤差的控制。在一般的試驗設計中&#xff0c;拉丁方常被看作雙區組設計&#xff0c;用于提高發現處理效應…

Skipped breakpoint at because it happened inside debugger evaluation親測可用

問題描述&#xff1a; 在多線程項目中&#xff0c;在idea中打斷點時&#xff0c;有時會遇到下面這種情況&#xff1a; idea左下角出現一行紅底或者綠底文字提示&#xff1a; Skipped breakpoint at because it happened inside debugger evaluation 然后我們能感受到的就是…

HTML中自定義鼠標右鍵菜單

今天突然有人跟我提到了HTML中如何自定義鼠標右鍵菜單&#xff0c;這里大概記錄一下吧&#xff0c;方便下次直接復制。免得還去看API文檔。 文章目錄 HTML中自定義鼠標右鍵菜單結果如下所示可以稍微改一下鼠標懸浮到右鍵菜單時的樣式結果如下所示 只在某個特定的div才可以顯示…

javascript 的eval()和with是干嘛的

原來JavaScript 中的eval() 和 with 是兩個強大的功能&#xff0c;但同時它們也具有潛在風險的特性&#xff0c;所以謹慎使用。 首先說說eval() 函數&#xff1a; 它接收一個字符串參數&#xff0c;并將其作為 JavaScript 代碼來解析和執行。 這意味著你可以使用 eval() 動態地…

《Scratch等級認證CCF-GESP真題解析》專欄總目錄

?? 專欄名稱:《Scratch等級認證CCF-GESP真題解析》 ?? 專欄介紹:中國計算機學會GESP《CCF編程能力等級認證》Scratch圖形化編程(1~4級)歷屆真題解析。 ?? 訂閱專欄:訂閱后可閱讀專欄內所有真題解析,真題持續更新中,限時9.9元,歡迎訂閱! Scratch圖形化編程一級 序…

2368. 受限條件下可到達節點的數目

2368. 受限條件下可到達節點的數目 題目鏈接&#xff1a;2368. 受限條件下可到達節點的數目 代碼如下&#xff1a; //深度優先遍歷 //參考&#xff1a;https://leetcode.cn/problems/reachable-nodes-with-restrictions/solutions/2662538/shu-shang-dfspythonjavacgojsrust-…

C++自學精簡實踐教程

一、介紹 1.1 教程特點 一篇文章從入門到就業有圖有真相&#xff0c;有測試用例&#xff0c;有作業&#xff1b;提供框架代碼&#xff0c;作業只需要代碼填空規范開發習慣&#xff0c;培養設計能力 1.2 參考書 唯一參考書《C Primer 第5版》?參考書下載&#xff1a; 藍奏云…

Acwing---3777. 磚塊

磚塊 1.題目2.基本思想3.代碼實現 1.題目 n 個磚塊排成一排&#xff0c;從左到右編號依次為 1~n。 每個磚塊要么是黑色的&#xff0c;要么是白色的。 現在你可以進行以下操作若干次&#xff08;可以是 0 次&#xff09;&#xff1a; 選擇兩個相鄰的磚塊&#xff0c;反轉它…

STL——stack

目錄 stack stack都有哪些接口 模擬實現一個stack stack 1. stack是一種容器適配器&#xff0c;專門用在具有后進先出操作的上下文環境中&#xff0c;其刪除只能從容器的一端進行元素的插入與提取操作。 2. stack是作為容器適配器被實現的&#xff0c;容器適配器即…

數據分析-Pandas數據的畫圖設置

數據分析-Pandas數據的畫圖設置 數據分析和處理中&#xff0c;難免會遇到各種數據&#xff0c;那么數據呈現怎樣的規律呢&#xff1f;不管金融數據&#xff0c;風控數據&#xff0c;營銷數據等等&#xff0c;莫不如此。如何通過圖示展示數據的規律&#xff1f; 數據表&#x…

春招!啟動了

大家好&#xff0c;我是洋子。今年的春招很多企業已經開始招聘了&#xff0c;像美團今年繼續發力&#xff0c;24屆春招以及25屆暑期轉正實習一共招聘4000人。另外&#xff0c;阿里&#xff0c;京東&#xff0c;順豐等公司也已經開始春招&#xff0c;可以說招聘的號角已經正式吹…

GO語言學習筆記(與Java的比較學習)(十)

錯誤處理與測試 Go 沒有像 Java 和 .NET 那樣的 try/catch 異常機制&#xff1a;不能執行拋異常操作。但是有一套 defer-panic-and-recover 機制 錯誤處理 Go 有一個預先定義的 error 接口類型 type error interface {Error() string } errors 包中有一個 errorString 結構…

十二、類與聲明

類與聲明 什么是類&#xff1f; 前情總結 前面22講的課基本上就做了兩件事 學習C#的基本元素學習類的成員 析構函數&#xff1a; 當對象不再被引用的時候&#xff0c;就會被垃圾回收器gc&#xff0c;回收。而收回的過程當中&#xff0c;如果需要做什么事情&#xff0c;就放在…