Invalid oauth2 token request

I am developing a node application that needs to be authenticated with google. When I request a token, https://accounts.google.com/o/oauth2/token responds:

error: 400 { "error" : "invalid_request" } 

I tried to make the same request in curl and got the same error, so I suspect that something is wrong with my request, but I can not understand what. I pasted my code below:

 var request = require('request'); var token_request='code='+req['query']['code']+ '&client_id={client id}'+ '&client_secret={client secret}'+ '&redirect_uri=http%3A%2F%2Fmassiveboom.com:3000'+ '&grant_type=authorization_code'; request( { method: 'POST', uri:'https://accounts.google.com/o/oauth2/token', body: token_request }, function (error, response, body) { if(response.statusCode == 201){ console.log('document fetched'); console.log(body); } else { console.log('error: '+ response.statusCode); console.log(body); } }); 

I checked triple to make sure that all the data I send is correct and I still get the same error. What can I do to debug this further?

+4
source share
3 answers

It turns out that request.js (https://github.com/mikeal/request) does not automatically include the length of the content in the headers. I added it manually, and it worked on the first try. I pasted the code below:

 exports.get_token = function(req,success,fail){ var token; var request = require('request'); var credentials = require('../config/credentials'); var google_credentials=credentials.fetch('google'); var token_request='code='+req['query']['code']+ '&client_id='+google_credentials['client_id']+ '&client_secret='+google_credentials['client_secret']+ '&redirect_uri=http%3A%2F%2Fmyurl.com:3000%2Fauth'+ '&grant_type=authorization_code'; var request_length = token_request.length; console.log("requesting: "+token_request); request( { method: 'POST', headers: {'Content-length': request_length, 'Content-type':'application/x-www-form-urlencoded'}, uri:'https://accounts.google.com/o/oauth2/token', body: token_request }, function (error, response, body) { if(response.statusCode == 200){ console.log('document fetched'); token=body['access_token']; store_token(body); if(success){ success(token); } } else { console.log('error: '+ response.statusCode); console.log(body) if(fail){ fail(); } } } ); } 
+3
source

from here How do I make an HTTP POST request in node.js? , you can use querystring.stringify to avoid the query string of query parameters. In addition, you'd better add 'Content-Type': 'application/x-www-form-urlencoded' for the POST request.

+1
source

place here the final line generated from token_request var.that, maybe something is wrong. or the authentication code may have expired or incorrectly added to the URL. Typically, the code has a '/', which should be escaped.

0
source

Source: https://habr.com/ru/post/1415905/


All Articles