How to validate Google Token ID sent from Android on Ruby on Rails server?
Asked Answered
B

1

5

I have an android app with Google sign-in. As per the documentation, I generated a token ID:

// Configure Google Sign-In with the requestIdToken

GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.server_client_id))
                .requestEmail()
                .build();

// Handle result

private void handleSignInResult(GoogleSignInResult result) {
    if (result.isSuccess()) {
        GoogleSignInAccount account = result.getSignInAccount();
        String tokenId = account.getIdToken();
    }
}

I'm facing the problem on the server side, with Ruby on Rails. I'm trying to use google-id-token gem. The README gives the following example:

validator = GoogleIDToken::Validator.new(expiry: 1800)
begin
  payload = validator.check(token, required_audience, required_client_id)
  email = payload['email']
rescue GoogleIDToken::ValidationError => e
  report "Cannot validate: #{e}"
end

I have the token (from the android java code). What is required_audience? Should I use the same client_id of my client app? When I try to run the code on server, I'm getting payload as nil.

Also, I would like to know if this is the right way to verify the token ID.

Byword answered 23/7, 2017 at 7:49 Comment(0)
B
9

After some research, I found answers to my own questions. Here are they:

What is required_audience?

It can be obtained from decoded JWT string. You can decode it as follows:

JWT.decode(token, nil, false)

Should I use the same client_id of my client app?

Yes. The required_audience and required_client_id should be same. Otherwise, verification fails

Then why was I getting payload as nil?

The problem is, the gem in GitHub and the one in RubyGems are different. I solved this problem by pointing Gemfile gem to GitHub:

gem 'google-id-token', git: 'https://github.com/google/google-id-token.git'
Byword answered 25/7, 2017 at 16:37 Comment(3)
Thanks for the clarification, but I still get Token not verified as issued by Google or nil respectively – even with my firebase project id for audience AND client id as well as with the gem from github. Any ideas why that is?Morelli
No, I didn't try the google-id-token gem yet. Will try that, thanks.Morelli
required_audience is not the entire JWT token, but the 'aud' key inside the decoded token. So to clarify: required_audience = JWT.decode(token, nil, false)[0]['aud']Alsoran

© 2022 - 2024 — McMap. All rights reserved.