1
votes

I have an android application and web-server working together. Now I want user log in via google from android application (or use one of the google accounts on android). Then andriod application passes token to my web-server with service call... and here I can't realise how to get user email or profile data from google having that token.

I can make a call like this in my browser: https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

But how to do that using google libraries? What library to use and so on?

3

3 Answers

1
votes

I used the code sample from here: https://github.com/googleplus/gplus-verifytoken-java which seem to be more up to date. The code ended up being something like:

GoogleCredential credential = new GoogleCredential().setAccessToken( accessToken );
Oauth2 oauth2 = new Oauth2.Builder(
    UrlFetchTransport.getDefaultInstance(),
    JacksonFactory.getDefaultInstance(), credential )
    .build();
Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken( accessToken ).execute();

// ... check tokeninfo expiry and issued to etc ...
1
votes

Depending on which service you try to use, just pick the right one of Google's Client Libraries and check out the Google+ Sample.

The first half should be basically the same for all APIs. For getting the User info, you would need the oauth2 library and then do something like this (taken from this example):

// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();

// Set up OAuth 2.0 access of protected resources
// using the refresh and access tokens, automatically
// refreshing the access token when it expires
GoogleAccessProtectedResource requestInitializer =
    new GoogleAccessProtectedResource(accessToken, httpTransport,
    jsonFactory, clientId, clientSecret, refreshToken);

// set up global Oauth2 instance
Oauth2 oauth2 = new Oauth2.Builder(httpTransport, jsonFactory, requestInitializer)
    .setApplicationName("Google-OAuth2Sample/1.0").build();

Userinfo userinfo = oauth2.userinfo().get().execute();
0
votes

You will need this library google-api-client JAR. Here is the working code how to do it. Keep Handy your ID_TOKEN and CLIENT_ID.

String jwt = "YOUR_ID_TOKEN";
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(),new GsonFactory())
                        .setAudience(Collections.singletonList("YOUR_CLIENT_ID"))
                        .build();
        
    GoogleIdToken idToken;
        
    try {
          idToken = verifier.verify(jwt);
        } catch (GeneralSecurityException e) {
           throw new RuntimeException("Cannot verify the ID_TOKEN send :" + e.getMessage());
        }
        
    if(idToken == null){
          throw new RuntimeException("Failed to verify the ID_TOKEN send");
        }
        
    String username =  idToken.getPayload().getEmail();