首页 > 解决方案 > 使用 Auth0 对令牌进行身份验证后如何检索用户信息

问题描述

我在用户登录网站时使用 Auth0 对用户进行身份验证,我使用 rails 作为后端,而对于前端,我使用 React。我可以从前端获取令牌并将其发送到后端以对用户进行身份验证,但我还无法提取用户信息。这是我正在使用向我的后端发出请求的代码

  const callProtectedApi = async () => {
    try {
      const token = await getAccessTokenSilently();
      console.log(token)
      const response = await axios.get('http://localhost:5000/private', {
        headers: {
          authorization: `Bearer ${token}`,
        },
      });
      console.log(response.data);
    } catch (error) {
      console.log(error.messsage);
    }   };

这是我在rails后端创建的方法

class PrivateController < ActionController::API
  def index
    require 'faraday'

    url = 'https://dev-v88tfgqc.us.auth0.com/userinfo'

    access_token = request.headers['authorization'].split(' ').last
    puts access_token
    response = Faraday.get(url, { 'authorization' => 'Bearer' + access_token })
    p response.status
    p response.body
    response = Faraday.get(url,
                           { 'authorization' => 'Bearer' + access_token })
  end
end

我可以在 Rails 中的服务器中打印令牌,但我无法从用户那里检索信息,因为我得到代码 401 并且未经授权,但这就是我没有得到的,因为我能够打印令牌,所以为什么我没有被授权? 在此处输入图像描述

标签: ruby-on-railsreactjs

解决方案


推荐阅读