Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 362
Yedhu Krishnan Avatar asked Jul 23 '17 07:07

Yedhu Krishnan


1 Answers

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'
like image 189
Yedhu Krishnan Avatar answered Nov 06 '22 02:11

Yedhu Krishnan