我正在尝试构建对 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"
}
显然授权类型不正确,但我不知道如何根据 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();
希望这对您有所帮助。不幸的是,我对请求库不够熟悉,无法提供使用它的示例。
关于javascript - Node JS - 构建 OAuth2 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37187429/