Similar to a previous article about Facebook tokens, I am going to explain how to verify, in an API, that users authenticated successfully with Google in a mobile app.
First step is to get the client IDs and secrets. It is explained in the Acquiring client IDs and secrets section of the Google Oauth 2.0 Guide.
Buried deep in the Google guides vortex, we can find what the mobile app has to do in the Authenticate with a backend server guide, Send the ID token to your server section. Basically the app will authenticate the user with Google and will get a ID token returned. The app must then send the ID token to the API.
In the API, we must decode the ID token to get the real Google user ID. To do that, we will use the Signet gem for Ruby. If you don’t use Ruby, you can check the other libraries Google offers.
Initialize the OAuth 2.0 client:
require 'signet/oauth_2/client'
client = Signet::OAuth2::Client.new(client_id: google_client_id, client_secret: google_client_secret)
Assign the ID token received from the app to the client:
client.id_token = id_token_from_the_app
Finally, decode the token:
payload = client.decoded_id_token
The Google user ID will be in payload['sub']
if the token was successfully decoded.