3)OAuth2 Client 結合GitHub授權案例
本隨筆說明:這僅作為OAuth2 Client初次使用的案例,所以寫得很簡單,有許多的不足之處,
OAuth2 Client(OAuth2客戶端)是指使用OAuth2協議與授權服務器進行通信并獲取訪問令牌的應用程式或服務,OAuth2客戶端代表最終用戶(資源擁有者)向授權服務器請求授權,并使用授權后的訪問令牌來訪問受保護的資源服務器,
OAuth2客戶端的主要任務是與授權服務器進行身份驗證和授權流程,以獲取訪問令牌,這樣,它可以使用該令牌來向資源服務器發出請求,獲取和操作受保護的資源,
OAuth2客戶端通常包含以下功能和組件:
-
客戶端憑據(Client Credentials):OAuth2客戶端必須擁有一個唯一的客戶端憑據,包括客戶端ID和客戶端密鑰(或密碼),這些憑據用于在與授權服務器進行通信時進行身份驗證和授權,
-
授權請求:OAuth2客戶端向授權服務器發送授權請求,包括請求的權限范圍和重定向URL,它會提供自己的客戶端憑據以進行身份驗證,
-
授權回呼處理:OAuth2客戶端需要能夠接收和處理來自授權服務器的授權回呼,這是授權服務器將授權碼或訪問令牌傳遞回客戶端的方式,
-
訪問令牌的管理:OAuth2客戶端負責管理訪問令牌的獲取、重繪和失效,它應該能夠安全地存盤和使用
3.1 GitHub設定
官方檔案:https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app
-
點擊自己頭像/進入
Settings
/ 進入Developer settings
(左邊導航欄最下面)/ 進入OAuth Apps
;然后注冊新應用程式 -
注冊新應用程式
第一步:
值得注意的是,如果回呼地址不是
/login/oauth2/code/*
,僅僅是回呼失敗,但是授權會成功,其次就是在spring security中/login/oauth2/code
是固定的,而/github
是自己指定的,即最后一個是動態的,從spring security原始碼中可以看出,回呼地址的固定寫法:
public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String DEFAULT_FILTER_PROCESSES_URI = "/login/oauth2/code/*"; private static final String AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE = "authorization_request_not_found"; private static final String CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE = "client_registration_not_found"; private ClientRegistrationRepository clientRegistrationRepository; private OAuth2AuthorizedClientRepository authorizedClientRepository; private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository; private Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter; public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService) { this(clientRegistrationRepository, authorizedClientService, "/login/oauth2/code/*"); } //省略..... }
第二步:點擊
Register application
后就會跳轉到如下界面,這時可以創建密鑰(必須)和上傳應用logo(非必須)創建密鑰時需要輸入密碼,得到密鑰后請妥善保存,更新資訊后密鑰就不再顯示
在更新前可以將
ClientID
和Client secrets
以及回呼URL
保存一下,等下會用到
3.2 開始編碼
創建一個基本的springboot專案,我這里的spring boot版本是:2.7.11,所以spring security的版本是5.7以上的,可能存在語法差異
-
spring security和oauth2 client的maven依賴
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <!--oauth2-client--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency>
-
yml組態檔
spring.security.oauth2.client.registration
是固定寫法,會有提示,而后面的為自定義內容,不會有提示server: port: 8080 spring: security: oauth2: client: registration: github: client-id: Client ID # 自己的客戶端ID client-secret: Client secrets # 自己的密鑰 redirect-uri: 回呼URL # 必須和GitHub上填的回呼地址一致
-
SpringSecurity組態檔
.oauth2Login()
使用oauth2登錄認證package com.yang.springsecurityoauthclient01.config; //省略導包 @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true) public class WebSecurityConfig { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http.authorizeRequests() .anyRequest().authenticated() .and() .oauth2Login() //使用oauth2認證 (需要在組態檔中配置服務,否則可能會啟動失敗 ) .and() .csrf().disable() .build(); } }
-
controller 控制層撰寫
package com.yang.springsecurityoauthclient01.controller; //省略導包 @RestController public class HelloController { @GetMapping("/index") public String index(){ return "主頁~~~"; } /** * @return GitHub的授權資訊 */ @GetMapping("/hello") public DefaultOAuth2User hello(){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return (DefaultOAuth2User) authentication.getPrincipal(); } }
-
最終結果
訪問
http://localhost:8080/index
,點擊GitHub進行授權驗證授權Authorize
訪問
http://localhost:8080/hello
得到授權資訊: -
撤銷用戶授權
撤銷授權后重啟程式,之前的用戶就需要進行重新進行授權了,
最后最后需要注意的是,同一個賬號在短時間內別試得太多,不然會出現如下情況,解決辦法也很簡單,等就是了~~~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/551906.html
標籤:其他
上一篇:原來Spring能注入集合和Map的computeIfAbsent是這么好用!
下一篇:返回列表