gpt4 book ai didi

node.js - Auth0/userinfo 端点返回未经授权的错误

转载 作者:搜寻专家 更新时间:2023-11-01 00:30:03 24 4
gpt4 key购买 nike

即使我在 Node.js 应用程序中传递不记名 token ,它也会给出未授权的结果错误。

    function getUser(authData){
var postData = querystring.stringify({ authorization: authData });

var options = {
host: 'pole.auth0.com',
method: 'GET',
path: '/userinfo'
};

//make request
httpsRequest(postData, options)
.then(function(result) {
// success
res.status(201).send({ 'success': true });
}, function(err) {
res.status(500).send({ 'success': false, 'reasonCode': "Internal error." });
});
};

辅助函数:

function httpsRequest (data, options) {
return new Promise(function (resolve, reject) {
var req = https.request(options, function (res) {
var result = '';
console.log(options);
res.on('data', function (chunk) {
result += chunk;
});
res.on('end', function () {
console.log("https end result - " + result);
resolve(result);
});
res.on('error', function (err) {
reject(err);
})
});

// req error
req.on('error', function (err) {
reject(err);
});

//send request witht the postData form
req.write(data);
req.end();
});
}

authData 参数有一个类似于 Bearer [token] 的字符串值。我正在使用 https.request 发出 api 请求

代码有什么问题吗?

最佳答案

根据/userinfo endpoint documentation你应该执行 GET HTTP 请求而不是 POST此外,您需要在 Authorization 中传递访问 token 标题。


更新:

问题在于您如何尝试在授权 header 中传递 token 。

您没有提到您使用什么作为 HTTP 客户端,但这里有一些使用 request-promise 的示例代码作为 Node HTTP 客户端;这很好用。

var rp = require('request-promise');

var options = {
uri: 'https://[YOUR_TENANT].auth0.com/userinfo',
headers: {
'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]'
}
};

rp(options)
.then(function (info) {
console.log('User information:', info);
})
.catch(function (err) {
// API call failed...
});

更新 2:

使用 Node.js 内置 HTTP 客户端:

const https = require('https');

var options = {
hostname: '[YOUR_TENANT].auth0.com',
port: 443,
path: '/userinfo',
method: 'GET',
headers: {
'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]'
}
};

var req = https.request(options, (res) => {
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.end();

req.on('error', (e) => {
console.error(e);
});

同样,重要的部分是如何在正确的 header 中传递 token 。

关于node.js - Auth0/userinfo 端点返回未经授权的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39847183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com