Aaron Balthaser
Aaron Balthaser

Reputation: 2622

Node JS - Constructing an OAuth2 Request

Im trying to construct an OAuth2 request to the Box API. The example POST request they give as a guideline is a bit ambiguous to me as I am recently learning backend development. The example is as follows:

POST /token
Content-Type: application/x-www-form-urlencoded
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&
assertion=<JWT>&
client_id=<client_id>&
client_secret=<client_secret>

Official Docs: https://box-content.readme.io/docs/app-auth

The way I attempted to do this is as follows:

var boxHeaders = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

var boxOptions = {
  url: 'https://api.box.com/oauth2/token',
  method: 'POST',
  headers: boxHeaders,
  form: {
    'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion': boxtoken,
    'client_id': 'myclientid',
    'client_secret': 'myclientsecret'
  }
};

request.post(boxOptions, function(err, response, body) {
  console.log(body);
});

I get the following error:

{
  "error":"invalid_request",
  "error_description":"Invalid grant_type parameter or parameter missing"
}

Obviously the grant type is incorrect but I have no idea how to go about constructing the string based on the Box API example. If anyone can help and even expose me to some good articles or tutorials on how to do this, that would be great!

Thank you.

Upvotes: 2

Views: 2331

Answers (1)

Sarah Pads
Sarah Pads

Reputation: 11

I just struggled with this myself. I was able to get this to work by moving everything you currently have in boxOptions.form into the request body.

For example:

var boxHeaders = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

var boxOptions = {
  url: 'https://api.box.com/oauth2/token',
  method: 'POST',
  headers: boxHeaders
};

var form = {
  grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer',
  client_id: 'id',
  client_secret: 'secret',
  assertion: boxtoken
};

var request = https.request(boxOptions, function(response) {
  // do stuff
});

request.write(querystring.stringify(form));
request.end();

Hope this helps. Unfortunately, I'm not familiar enough with the request library to provide an example using it.

Upvotes: 1

Related Questions