代码之家  ›  专栏  ›  技术社区  ›  Taylor Austin

/api/v2/users/{id}缺少身份验证Auth0

  •  3
  • Taylor Austin  · 技术社区  · 7 年前

    我已经拿到了到达终点的令牌 /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错误和消息。我不确定我与邮递员和我的应用程序有什么不同,但我做错了什么。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Aniruddh Agarwal    7 年前

    您没有像应该的那样传递标题

    你应该这样做:

    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()
    

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

        2
  •  0
  •   arcseldon    7 年前

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

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

    最后,如果postman正在工作,您还可以尝试生成代码段选项,并使用导出工作示例 request (node.js)。如果可行,请沿相同的线修改为Axios。请随时在下面的评论中发布问题。