Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Google OAuth 2.0 Access token directly using curl? (without using Google Libraries)

I'm trying to follow this tutorial to authenticate with Google using their OAuth 2.0 API. However, I would like to make straight curl calls rather than use their libraries.

I have obtained my Client ID and Client Secret Key. Now I'm trying to get the access token like this:

curl \
--request POST \
--header "Content-Type: application/json" \
--data '{
  "client_id":"MY_CLIENT_ID",
  "client_secret":"MY_SECRET_KEY",
  "redirect_uri": "http://localhost/etc",
  "grant_type":"authorization_code"
}' \
"https://accounts.google.com/o/oauth2/token"

However, it is not working. It gives me the following error:

{
  "error" : "invalid_request",
  "error_description" : "Required parameter is missing: grant_type"
}

Can someone please provide me sample curl call to obtain the access token (and refresh token)?

like image 732
Saqib Ali Avatar asked May 09 '16 04:05

Saqib Ali


People also ask

How do I get my cURL access token?

To generate an access token: Replace {AUTH CODE QUERY PARAMETER} with the auth code you copied from the previous step in the above cURL request. Replace {CLIENT ID} in the above request with the Client ID from your Oauth client. Replace {CLIENT SECRET} in the above request with the Client Secret from your Oauth client.

How can I get Google Auth token for testing?

The best solution to this currently is to log in to a Google account, capture the Google cookies for this session, then use these same cookies to acquire an authorization code in your tests later. Each time the test runs, it can create an authorization code and exchange this for an access token.


2 Answers

a) the data you provide should be form-encoded instead of presented as a JSON object and b) you should also provide an authorization code value in the "code" parameter. E.g.:

curl -d "client_id=MY_CLIENT_ID&\
  client_secret=MY_SECRET_KEY&\
  redirect_uri=http://localhost/etc&\
  grant_type=authorization_code&\
  code=CODE" https://oauth2.googleapis.com/token
like image 175
Hans Z. Avatar answered Oct 24 '22 04:10

Hans Z.


While not directly using CURL, you can also get and test OAuth tokens using the Google OAuth Playground: https://developers.google.com/oauthplayground/

like image 35
Tad Avatar answered Oct 24 '22 06:10

Tad