0

I try to get the userinfo after successfully authenticate with a gmail account (tok is a valid token):

        GoogleCredential credential2 = new GoogleCredential.Builder()
                .setTransport(TRANSPORT).setJsonFactory(JSON_FACTORY)
                .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
                .setRequestInitializer((new HttpRequestInitializer() {
                    @Override
                    public void initialize(HttpRequest request)
                            throws IOException {
                        request.getHeaders().setAuthorization("Bearer ".concat(tok));
                    }
                }))
                .build();

        Oauth2 userInfoService = new Oauth2.Builder(TRANSPORT,
                JSON_FACTORY, credential2.getRequestInitializer())
                .setApplicationName(APPLICATION_NAME).build();

        Userinfo userInfo = userInfoService.userinfo().get().execute();
        logger.warn("User email: {}", userInfo.getEmail());
        logger.warn("User gender: {}", userInfo.getGender());
        logger.warn("User complet name: {} - {}", userInfo.getFamilyName(), userInfo.getName());

But logs display 'null' for all fields, the json data returned contains only the id:

{
 "id": "113695880661351193041"
}

What i'm supposed to do ? Add a special scope to do this? I tried it several times without success, just by adding scope=https://www.googleapis.com/auth/userinfo.profile as url parameter, maybe that's wrong ?

Hope someone can help or know how to add scopes to my request and get the correct response from this service.

kij
  • 1,421
  • 1
  • 16
  • 40

1 Answers1

1

This works for me :

Credential credential = OAuth2Utils.newFlow().loadCredential(userId);

Oauth2 service = new Oauth2.Builder(OAuth2Utils.HTTP_TRANSPORT, OAuth2Utils.JSON_FACTORY, credential).setApplicationName("appname").build();

UserInfo userInfo = service.userinfo().get().execute();

These are some of the properties that are returned :

  • userInfo.getBirthday()

  • userInfo.getFamilyName()

  • userInfo.getGender()

  • userInfo.getGivenName()

  • userInfo.getHd()

  • userInfo.getLink()

The utility class OAuth2Utils referred in the code :

/** Global instance of the HTTP transport. */
public final static HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();

/** Global instance of the JSON factory. */
public final static com.google.api.client.json.JsonFactory JSON_FACTORY = new com.google.api.client.json.jackson2.JacksonFactory();

public static GoogleAuthorizationCodeFlow newFlow() throws IOException {
    return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientCredential(),
            Arrays.asList(SCOPES)).setCredentialStore(new OAuth2CredentialStore()).setAccessType("offline")
            .setApprovalPrompt("force").build();
}
koma
  • 6,486
  • 2
  • 27
  • 53