[英]Get User Details After Social Login via OAuth2
我正在開發一個 spring 啟動應用程序,並且我有一個身份驗證步驟。我正在使用 spring 安全性和 spring-boot-starter-oauth2-client。 我希望我的用戶可以使用谷歌登錄。
我已經閱讀了很多關於使用 oauth2 進行社交登錄的文章,它們正在進行簡單的配置及其工作。每當我嘗試相同的步驟時,它對我都不起作用。 我覺得我錯過了一點。
他已經完成了;
1 - 在 application.yml 我把下面的 conf。
spring:
security:
oauth2:
client:
registration:
google:
clientId: 876826483277-eap24vioi12cp4bjld5bqr8hir0t5kfl.apps.googleusercontent.com
clientSecret: bm3HkBDhYmycEnRwAFbR1-mL
redirectUri: http://localhost:8090/callback
scope:
- email
- profile
2 - 這是我的 WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/callback/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
// @formatter:on
}
}
3 - 這是我的樣品 rest 資源
@RestController
public class OAuth2Resource {
@RequestMapping(method = RequestMethod.GET, value = "/callback")
public String callback(@RequestParam Map<String, String> requestParamMap) {
System.out.println("Code = " + requestParamMap.get("code"));
return "OK";
}
}
4 - 這是我的redirectURL conf。 在我的谷歌帳戶上
http://localhost:8090/callback
它最多可以重定向到回調 rest api,在回調中我可以獲得“代碼”字段值,但要注意更多。我的問題是,如何獲取用戶詳細信息,例如名稱,Z0C83F57C786A0B4A39EFAB23C731 回調方法應該如何?
注意:我嘗試設置
.oauth2Login().successHandler(oAuth2AuthenticationSuccessHandler)
或者
.oauth2Login().defaultSuccessUrl("/loginSuccess")
在我的 HttpSecurity 配置中,但甚至沒有觸發
根據RFC 6749 - 第 4.1 節。 授權代碼授予此流程(授權代碼授予,由 Spring Security 實現)您應該使用正確的授權代碼從授權服務器重定向到您的提供商(谷歌)的令牌端點。
+----------+
| Resource |
| Owner |
| |
+----------+
^
|
(B)
+----|-----+ Client Identifier +---------------+
| -+----(A)-- & Redirection URI ---->| |
| User- | | Authorization |
| Agent -+----(B)-- User authenticates --->| Server |
| | | |
| -+----(C)-- Authorization Code ---<| |
+-|----|---+ +---------------+
| | ^ v
(A) (C) | |
| | | |
^ v | |
+---------+ | |
| |>---(D)-- Authorization Code ---------' |
| Client | & Redirection URI |
| | |
| |<---(E)----- Access Token -------------------'
+---------+ (w/ Optional Refresh Token)
Spring Security 的此端點模板是:
{baseUrl}/login/oauth2/code/{registrationId}
對你來說,這將是:
http://localhost:8090/login/oauth2/code/google/
(假設 8090 是您的 Spring 啟動應用程序的端口)
代碼將由 Spring 自動添加。 正確驗證后,您將再次被重定向,您的客戶端(您的應用程序)將有權訪問您請求的 scope。 您應該能夠使用以下方法看到這一點:
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
我希望這有幫助。 我知道 oauth 登錄可能會很痛苦,所以祝你好運,不要放棄;-)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.