Node JS-构造OAuth2请求

Node JS - Constructing an OAuth2 Request

本文关键字:请求 OAuth2 构造 JS- Node      更新时间:2023-09-26

我试图构造一个到Box API的OAuth2请求。他们作为指导原则给出的POST请求示例对我来说有点模糊,因为我最近正在学习后端开发。示例如下:

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>

官方文件:https://box-content.readme.io/docs/app-auth

我尝试这样做的方式如下:

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

我得到以下错误:

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

显然,grant类型是不正确的,但我不知道如何基于Box API示例构建字符串。如果有人能帮助我,甚至让我了解一些关于如何做到这一点的好文章或教程,那就太好了!

谢谢。

我只是自己在挣扎。我可以通过将您当前在boxOptions.form中的所有内容移动到请求正文中来实现这一点。

例如:

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

希望这能有所帮助。不幸的是,我对请求库不够熟悉,无法提供使用它的示例。