【问题标题】:Missing Authentication Auth0 for /api/v2/users/{id}/api/v2/users/{id} 缺少身份验证 Auth0
【发布时间】:2018-09-08 12:39:16
【问题描述】:

我已经从到达终点/oauth/token 获得了令牌,并通过邮递员将其通过标题传递给/api/v2/users/{id},就像这样

{Authorization: `Bearer ${token}`}

在邮递员上它工作得很好,并把用户还给我。但是,当我在我的应用程序中执行此操作时,我会返回 401 错误。我正在使用 axios 并像这样传递令牌。

return new Promise((resolve, reject) => {
    axios
      .post('https://taustin.auth0.com/oauth/token', body, headers)
      .then(res => {
        resolve(res.data.access_token);
      })
      .catch(err => {
        reject(err);
      });
  });

上面是generateToken函数。

generateToken()
          .then(token => {
            const headers = { Authorization: `Bearer ${token}` };
            console.log(token); //token is valid here
            axios
              .get(
                `https://taustin.auth0.com/api/v2/users/${profile.sub}`,
                headers
              )
              .then(res => {
                console.log(res);
              });
          })

在 catch 块中,我收到 401 unauth 错误和消息。我不确定我在做什么与邮递员和我的应用程序不同,但我做错了。

【问题讨论】:

  • 其余的请求头是否相同? Content-type、Accept、Referer 和 Origin?
  • 你能展示1)获取令牌2)传递令牌的整个流程吗?两者之间可能存在导致问题的原因
  • @GaborLengyel 是的,标题是相同的。猎人将进行编辑
  • @TaylorAustin 尝试将标头包装在对象文字中,我相信 GET 的所有选项都必须作为单个对象传递:axios.get(URL, { headers })

标签: javascript axios auth0


【解决方案1】:

如果您不确定是否正确设置了 Axios,请查看 this react sample(几个月前写的,但应该仍然相关)。

如果您的问题不在于您如何塑造 Axios 请求,而在于其他问题,请检查访问令牌。例如,实际使用您在应用程序中使用的访问令牌,并通过 Postman 尝试相同的访问令牌。如果您的访问令牌不是 opaque,而是 JWT 访问令牌,请检查 audience 值。它应该符合https://taustin.auth0.com/userinfo/

最后,如果邮递员正在工作,您还可以尝试生成代码 sn-p 选项,并使用 request (node.js) 导出工作示例。然后,如果可行,请按照相同的方式修改 Axios。随时在下面的 cmets 中发布问题。

【讨论】:

    【解决方案2】:

    您没有按应有的方式传递标头

    你应该这样做:

    const headers = { Authorization: `Bearer ${token}` };
    axios
     .get(
       `https://taustin.auth0.com/api/v2/users/${profile.sub}`,
       headers: headers
     ).then().catch()
    

    或者这样试试

    axios
     .get(
       `https://taustin.auth0.com/api/v2/users/${profile.sub}`,
       headers: {`Authorization: `Bearer ${token}`}
     ).then().catch()
    

    希望这些对您有所帮助,如果您需要更多帮助,请回复。

    【讨论】:

    • 我完全忘记了 axios 是用 get 做的,谢谢!
    • 完全没问题。欢迎!
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2015-04-10
    • 2017-04-27
    • 2015-06-01
    • 2019-03-25
    • 2020-09-18
    相关资源
    最近更新 更多