0
votes

I'm trying to implement a process which combines Google sign-in on client side (Web page) with server side verification and query user data (Java server).

What I did:

  1. In Google developer console, added an OAuth 2.0 client IDs credential.

  2. Implemented the sign-in on the web page and got the ID token after successful login.

  3. Implemented the authentication with a backend server as explained here: https://developers.google.com/identity/sign-in/web/backend-auth. This part also works and I can verify the authentication and get the user's e-mail address.

What I need to do now is getting the user's profile information, i.e. first and last name and access the app folder, to store relevant application data.

This is my server side code. I marked the part where I need help:

GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(HTTP_TRANSPORT, JSON_FACTORY)
.setAudience(Arrays.asList(service.getClientId()))
.build();

GoogleIdToken idToken = null;
try {
    idToken = verifier.verify(token); // token is the ID token received from the client
} catch (GeneralSecurityException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
if (idToken != null) {
    GoogleIdToken.Payload payload = idToken.getPayload();
    payload.getEmail() <== This works

    /*
    Here I need to query Google API per the available application scopes: profile, app storage etc.
    */
}

Is it possible to use the API at this stage? If not, can I request access token here? Should I use the Client ID or do I need a different type of credential (like API key or Service account)?

1

1 Answers

1
votes

ID Token represents authentication, not authorization. So you won't be able to access Google APIs just with ID Token.

In order to make requests to Google APIs from server side, do following on client side.

var auth2 = gapi.auth2.getAuthInstance();
auth2.grantOfflineAccess({
  scope: 'SCOPES_COMES_HERE'
}).then(function(resp) {
  // send `resp.code` to server to exchange it with
  // credentials (access_token, refresh_token
});

The code is the key to exchange with access_token.

You might be inclined to implement authentication and authorization at the same time, but Google's recommendation is to separate them and request permissions as they are needed (incremental authorization). Leave the current code and add above + server side that handles code to exchange with access_token.

Detailed doc: https://developers.google.com/identity/sign-in/web/server-side-flow