Search code examples
javagoogle-oauth

GoogleAuthorizationCodeFlow


After making a call to:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(
        dataStoreFactory).build();
Credential cred = flow.loadCredential(userIdFromMyApplication);

And finding our userIdFromMyApplication has not yet given us permission to use their Google account (i.e. cred is null) I do the following:

if (cred == null) {
  String url = flow.newAuthorizationUrl().setState("/linkaccount")
     .setRedirectUri("http://myapp.com/oauth2.php").build();
  //redirect them to the url    
}

My question is, once they've granted my app access and my app's oauth2 redirect url I setup under my API access token is called by Google with the access code parameter set, how do I then associate this code with userIdFromMyApplication ? Would I have to set userIdFromMyApplication within my call to setState when building the redirectUrl? Is that a viable convention? Or is there a more clever way to figure out what access token belongs to which user?


Solution

  • Either store the user ID in your httpSession, or add the user ID (ideally obfuscated) to the "state" parameter, which will then get included in the oauth callback. Personally I use httpSession.

    Actually, the second method might pose a security risk, so go with the httpSession.