6

I have tried just about everything, read every StackOverflow post on this issue but I still can't get it to work. Interestingly enough, I am able to get 200 OK response when sending a POST request via DHC REST API Client (Google Chrome app).

  var url = 'https://accounts.google.com/o/oauth2/token';
  var params = querystring.stringify({
    grant_type: 'authorization_code',
    code: req.body.code,
    client_id: req.body.clientId,
    client_secret: 'HIDDEN',
    redirect_uri: req.body.redirectUri
  });
  params = querystring.unescape(params); // doesn't work with or without string escaping

  request.post(url + '?' + params, function(error, response, body) {
    console.log(body);
  });

enter image description here

enter image description here

Sahat Yalkabov
  • 32,654
  • 43
  • 110
  • 175

2 Answers2

8

As @BenFortune has already mentioned, I was sending GET parameters as a POST request. It's amazing such a trivial thing has gone unnoticed after trying to figure it out for over an hour.

Now, I blame inconsistencies across OAuth providers for this. In the same application I am doing a GET request to Facebook to obtain access_token: https://graph.facebook.com/oauth/access_token. But Google expects a POST request to obtain access_token: https://accounts.google.com/o/oauth2/token

Correct version:

  var url = 'https://accounts.google.com/o/oauth2/token';
  var payload = {
    grant_type: 'authorization_code',
    code: req.body.code,
    client_id: req.body.clientId,
    client_secret: 'HIDDEN',
    redirect_uri: req.body.redirectUri
  };

  request.post(url, { form: payload }, function(error, response, body) {
    console.log(body);
  });
Sahat Yalkabov
  • 32,654
  • 43
  • 110
  • 175
  • Hi, I'm facing the same error. I tried what you did and I receive this error: `XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400. ` – Javi Jul 20 '15 at 22:26
  • omg, fu*ing postman, I was inserting url params instead of POST params... – Choletski Dec 14 '16 at 13:57
0

Check the request Encoding.

in my case i was sending .json and was .url

Using Alamofire 3.0

jose920405
  • 7,982
  • 6
  • 45
  • 71