简体   繁体   中英

Get User Details After Social Login via OAuth2

I'm developing a spring boot app and I have an authantication step.I'm using spring security and also spring-boot-starter-oauth2-client. I want my users can login with google.

I've read a lot of articles about social login with oauth2, they are making siple configurations and its working.Whenever I tried the same steps it did not work for me. I thing I'm missing little point.

He is all have done;

1 - In application.yml I put below 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 - This is my 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 - This is my sapmle rest resource

@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 - This my redirectURL conf. on my google account

http://localhost:8090/callback

It works up to redirecting to callback rest api, in callback I can get "code" field value but noting more.My question is, How can I get user details like name,email.. How should my callback method body be?

NOTE: I tried setting

.oauth2Login().successHandler(oAuth2AuthenticationSuccessHandler)

or

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

in my HttpSecurity configuration but not even triggered

According to RFC 6749 - section 4.1. Authorization Code Grant this flow (Authorization Code Grant, that is implemented by Spring Security) you should redirect from authorization server to token endpoint of your provider (google) with proper Authorization code.

     +----------+
     | 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)

This endpoint template for Spring Security is:
{baseUrl}/login/oauth2/code/{registrationId}
Which for you will be:
http://localhost:8090/login/oauth2/code/google/ (assuming 8090 is a port for your Spring Boot app)

Code will be automatically added by Spring. After correct validation you will be redirected again and you client (your app) will have access to scope that you requested for. You should be able to see this using:

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

I hope this helps. I know that oauth login can be a pain so good luck and don't give up;-).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM