chtefi
6/25/2017 - 1:52 PM

Easy OAuth2 with Google explained

Easy OAuth2 with Google explained

Here is the different steps to get a valid Access Token to query Google apis, manually.

Note that we should always use a proper library to do that automatically behind the scene (because it has to handle the refresh token route too).

  1. create an app on https://console.developers.google.com

  1. create a OAuth 2.0 client ID for this app
  • set a redirect_url to the live app http://example.com/oauth2callback. Google needs this to ensure it's talking to you.
  • this will provide a client_id and a client_secret

  1. GET
https://accounts.google.com/o/oauth2/auth?
client_id=424006053408-t3v4em804rcso.apps.googleusercontent.com
&redirect_uri=http://example.com/oauth2callback
&response_type=code
&scope=email
  • set a proper client_id, redirect_uri, scope and response_type
  • the scope determine which info we can access (the user will have the list and need to consent)
  • scope email is implicitly replaced by https://www.googleapis.com/auth/userinfo.email.
  • another scope is https://www.googleapis.com/auth/plus.login to grab the google plus profile data for instance

  1. Google redirects to http://example.com/oauth2callback?code=4/wKwdfCSuWD0tK5A-krKbWS7_ToA#
  • this code is a one-usage-time only
  • we need this code to ask google for the final access token we seek

  1. SERVER-SIDE, we POST
https://accounts.google.com/o/oauth2/token

client_id=424006053408-t3v4emgkqi6rcso.apps.googleusercontent.com
&code=4%2FjDREzDtWEPtZELmonN1oZpCNU
&client_secret=wDOY-Lj5bggktWNCa
&grant_type=authorization_code
&redirect_uri=http%3A%2F%2Fexample.com%2Foauth2callback
  • we must provide the previous code, the client_id, the client_secret (which is why it's server-side only!)

  1. we receive an access_token, id_token, and expires_in
{
    "access_token": "ya29.GltDFHu_0D1940sHXMF2yvLgFvKxqj0z_s1S1llGRd...",
    "expires_in": 3600,
    "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImJ...",
    "token_type": "Bearer"
}

  1. we can know call google apis with the token in the header: `Authorization: Bearer [token]
  • https://www.googleapis.com/oauth2/v2/userinfo returns some json with id, email and so on (if scope was email)
  • https://www.googleapis.com/plus/v1/people/me returns google plus data (if scope was plus.login)