Occasionally while working on a project I have need to test some calls to Googles APIs manually. To do that you need an access token. Getting an Access token can be a pain sometimes.
So i have created a simple CURL script that will show you how to authenticate to Google and get an access token.
You will need to go to Google developer console and create a client id for this its easier to use a type other client. By using type other we can avoid the need for a redirect URI, we don’t really need one as we are just going to run this as a curl script. If you are really worried about security you can lock the client to your ip address.
What you need are the following:
- Client ID
- Client Secret
- Scopes – the scopes define what access you will receive. you can have more then one just put a space between them. For this i am just going to use openid.
Now replace the values needed in the following link and put it in a web browser
https://accounts.google.com/o/oauth2/auth?client_id=[Application Client Id]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=[Scopes]&response_type=code
Exchanging Authentication code
You should get the standard request for authentication. Once you have accepted authentication copy the Authentication code. Take the following code replace the values as needed.
–request POST \
–data “code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code” \
You should get something like this:
Congratulations you now have an access token you can use in your Google API call. Just remember to use access_token= and not key= there is a difference.
Use Refresh Token
If your access token expires you can use the following command to refresh it using the Refresh token.
–request POST \
–data ‘client_id=[Application Client Id]&client_secret=[Application Client Secret]&refresh_token=[Refresh token granted by second step]&grant_type=refresh_token’ \
The response will be slightly diffrent this time. You wont get a new Refresh token.
“access_token” : “XXXXX”,
“expires_in” : 3600,
“id_token” : “xxxxx”,
“token_type” : “Bearer”
We can use a couple of simple curl commands to get an access token for use with Google APIs. There is a public Gist up on Github for this GoogleAuthenticationCurl.sh