【发布时间】:2021-11-02 17:48:27
【问题描述】:
我目前正在写入 API 以尝试获取令牌。我快到了,但在最后一道障碍中摔倒了..
const fs = require('fs');
const https = require('https');
const ConfigParams = JSON.parse(fs.readFileSync('Config.json', 'utf8'));
const jwt = require('jsonwebtoken');
const apikey = ConfigParams.client_id;
var privateKey = fs.readFileSync(**MY KEY**);
var tkn;
const jwtOptions = {
algorithm: 'RS512',
header: { kid: 'test-1' }
}
const jwtPayload = {
iss: apikey,
sub: apikey,
aud: **API TOKEN ENDPOINT**,
jti: '1',
exp: 300
}
jwt.sign(jwtPayload,
privateKey,
jwtOptions,
(err, token) => {
console.log(err);
//console.log(token);
tkn = token;
let = tokenPayload = {
grant_type: 'client_credentials',
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer/',
client_assertion: tkn
}
tokenAuthOptions = {
payload: tokenPayload,
host: **HOST**,
path: **PATH**,
method: 'POST',
}
https.request(
tokenAuthOptions,
resp => {
var body = '';
resp.on('data', function (chunk) {
body += chunk;
});
resp.on('end', function () {
console.log(body);
console.log(resp.statusCode);
});
}
).end();
}
)
编码的令牌在第一部分恢复正常,但 https 请求返回问题。
我得到的响应是缺少 grant_type,所以我知道由于这个 x-www-form-urlencoded,我遇到了格式问题,但我不知道如何解决它。
这是网站所说的:
您需要在请求正文中包含以下数据 x-www-form-urlencoded 格式:
grant_type = client_credentials client_assertion_type = urn:ietf:params:oauth:client-assertion-type:jwt-bearer client_assertion = 这是一个完整的 例如,作为 CURL 命令:
curl -X POST -H "content-type:application/x-www-form-urlencoded" --data \ "grant_type=client_credentials\ &client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion="
终点
理想情况下,我想要一个使用 https 请求的解决方案,但如果这不可能,我愿意接受其他解决方案。
非常感谢任何帮助。
谢谢, 克雷格
编辑 - 我根据以下建议更新了我的代码:
const params = new url.URLSearchParams({
grant_type: 'client_credentials',
client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer/',
client_assertion: tkn
});
axios.post("URL", params.toString()).then(resp => {
console.log("response was : " + resp.status);
}).catch(err => {
console.log("there was an error: " + err);
})
但我仍然收到错误代码 400,但现在没有详细说明原因。 (错误码400有多个消息失败)
【问题讨论】:
-
我在这里看不到选项
payload:nodejs.org/api/http.html#httprequestoptions-callback。最好使用got或axios之类的东西来发送此类请求。另外,请记住,对于x-www-form-urlencoded的正文,它不应该是 JSON,它应该是一个特殊的字符串。 -
感谢您的信息。我会尝试 Axios 而不是 https。如果有人以前做过类似的事情并且可以协助格式化,那就太好了。
-
也许像 axios 一样准备一个字符串就足够了,见这里github.com/axios/…
-
我刚上同一个网站 :) 我改成axios,改在主帖里。不幸的是,我现在在 catch 中收到错误 400,它给我的响应代码错误信息更少:(
-
因为您在 Node.js 中而不是在浏览器中执行所有这些操作,所以您需要使用
qs:github.com/axios/axios#nodejs