【发布时间】:2017-09-11 23:39:01
【问题描述】:
我正在尝试使用 Auth0 颁发 JWT 令牌以访问我的 API(以便 Auth0 处理所有 OAuth 和安全问题等,而我的 API 只需要检查令牌)。当我尝试测试客户端的授权代码流以接收访问令牌(使用 Node + Express)时,会发生以下情况:
授权代码请求工作正常,客户端被重定向回我的 redirect_uri,代码附加到查询中。一切都好。
然后令牌请求总是失败。如果我包含
audience参数,则请求将返回access_denied错误并包含以下详细信息:Service not found: {the audience parameter},无论我为audience参数设置了什么值。如果我不包含
audience参数,我会收到带有消息Service not found: https://oauth.auth0.com/userinfo的server_error。
我检查了每个 Auth0 设置并彻底阅读了每个文档页面,但到目前为止没有任何效果。我还在 Auth0 的 API 调试器中测试了授权代码流程,它运行良好。我的测试遵循完全相同的参数,但仍然收到请求令牌的错误。我正在本地主机上进行测试。客户端凭据和隐式流工作正常。
这是我创建的一个测试端点,它从 Auth0 检索授权码:
const qs = require('querystring');
const getCode = (req, res) => {
const params = {
audience, // the value of the API Audience setting for the client
client_id, // the client ID
redirect_uri, // the redirect_uri, which is also listed in the Allowed Callback URLs field
response_type: `code`,
scope: `offline_access open` // ask to return ID token and refresh token,
state: `12345`,
};
const authDomain = `mydomain.auth0.com/oauth`;
res.redirect(`${authDomain}/oauth/authorize?${qs.stringify(params)}`);
};
redirect_uri 然后重定向到以下端点,我在此请求访问令牌:
const https = require('https');
const callback = (req, res) => {
const body = {
client_id,
client_secret,
code: req.query.code,
grant_type: `authorization_code`,
redirect_uri, // same value as provided during the code request
};
const opts = {
headers: { 'Content-Type': `application/json` },
hostname: `mydomain.auth0.com`,
method: `POST`,
path: `/oauth/token`,
};
const request = https.request(opts, response => {
let data = ``;
response.on(`data`, chunk => { data += chunk; });
response.on(`error`, res.send(err.message));
response.on(`end`, () => res.json(JSON.parse(data))); // this executes, but displays the error returned from Auth0
});
request.on(`error`, err => res.send(err.message));
request.end(JSON.stringify(body), `utf8`);
};
关于我可能做错了什么有什么建议吗?
【问题讨论】:
-
实际包含您的代码可能是个好主意。否则,只是猜测。
-
我不熟悉
https.request...但是你为什么要对请求的正文进行字符串化? -
@MariaInesParnisari 内容类型为 application/json,因此正文必须采用正确的 JSON 字符串格式。如果我在代码中省略该步骤,请求将失败,只需执行
request.end(body)。 -
啊哈哈,有道理