通过 OAuth2 社交登录后获取用户详细信息

时间:2021-04-30 11:02:38

标签: java spring-boot spring-security spring-security-oauth2

我正在开发一个 spring 启动应用程序,我有一个认证步骤。我正在使用 spring 安全性和 spring-boot-starter-oauth2-client。我希望我的用户可以使用谷歌登录。

我已经阅读了很多关于使用 oauth2 进行社交登录的文章,他们正在制作 siple 配置及其工作。每当我尝试相同的步骤时,它对我不起作用。我觉得我遗漏了一点。

他已经完成了;

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 - 这是我的 sapmle 休息资源

@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。在我的 Google 帐户上

http://localhost:8090/callback

它可以重定向到回调rest api,在回调中我可以获得“代码”字段值但注意更多。我的问题是,如何获取用户详细信息,如姓名、电子邮件..我的回调方法主体应该如何?

注意:我试过设置

.oauth2Login().successHandler(oAuth2AuthenticationSuccessHandler)

.oauth2Login().defaultSuccessUrl("/loginSuccess")

在我的 HttpSecurity 配置中但没有触发

1 个答案:

答案 0 :(得分:0)

根据 RFC 6749 - section 4.1. Authorization Code Grant 此流程(授权代码授予,由 Spring Security 实现),您应该使用正确的授权代码从授权服务器重定向到您的提供商 (google) 的令牌端点。

     +----------+
     | 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 Boot 应用程序的端口)

Spring 会自动添加代码。正确验证后,您将再次被重定向,您的客户端(您的应用程序)将有权访问您请求的范围。您应该能够看到这一点:

SecurityContextHolder.getContext().getAuthentication().getPrincipal();

我希望这会有所帮助。我知道 oauth 登录可能会很痛苦,祝你好运,不要放弃;-)