Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
942 views
in Technique[技术] by (71.8m points)

node.js - Google OAuth2: Required parameter is missing: grant_type

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...