【问题标题】:How do I return the id property of the user object in Apollo?如何在 Apollo 中返回用户对象的 id 属性?
【发布时间】:2017-06-25 03:29:17
【问题描述】:

当我将以下内容放在查询用户模型的 React 组件中时,我能够获取 graphQL 查询的整个用户对象,包括 id 属性:

console.log(this.props.data.user)

但是当我尝试从代码中访问 id 属性时:

console.log(this.props.data.user) // undefined 
console.log(this.props.data.user.id)
 // error cannot get property of undefined 

我的第一个猜测是这是一个安全功能;我正在使用 Auth0 和 Graphcool。

但我可能只是以一种倒退的方式来解决这个问题。如果是这样,任何有关以正确方式访问用户 ID 的帮助将不胜感激。

谢谢

【问题讨论】:

    标签: reactjs graphql auth0 apollo graphcool


    【解决方案1】:

    FAQ article on the logged in user 对此进行了介绍。

    使用 Auth0 获取签名的 JWT

    user 查询返回当前经过身份验证的用户。所以首先我们要考虑如何确定认证用户。

    当前最先进的技术是 using verified JWT 并将它们作为 Authorization 标头传递。

    在 Auth0 Lock 中输入有效凭据后,它会返回一个使用您的秘密 Auth0 密钥签名的 JWT。这个签名的 JWT 被发送到 GraphQL 服务器,我们将在其中使用您的 Auth0 密钥对其进行验证,如果它属于有效用户,则对请求进行身份验证。

    使用 Apollo 客户端设置 Authorization 标头

    所以我怀疑您根本没有传递有效的 Authorization 标头。使用 Apollo,您可以使用它来确保传递令牌(如果存在)。请注意,我们将使用本地存储来存储来自 Auth0 Lock 的令牌:

    const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })
    
    // use the auth0IdToken in localStorage for authorized requests
    networkInterface.use([{
      applyMiddleware (req, next) {
        if (!req.options.headers) {
          req.options.headers = {}
        }
    
        // get the authentication token from local storage if it exists
        if (localStorage.getItem('auth0IdToken')) {
          req.options.headers.authorization = `Bearer ${localStorage.getItem('auth0IdToken')}`
        }
        next()
      },
    }])
    
    const client = new ApolloClient({ networkInterface })
    

    检查this Auth0 example codethe live demo 以了解其工作原理。

    您可能还对this answer on authorization (permissions) 感兴趣。

    【讨论】:

    • 谢谢,但我实际上正在使用您建议的 github 项目。它与身份验证、查询、突变一起工作。
    • 您能在您的代码周围添加更多上下文吗?也许你在data.loading之前访问data
    • 之前data.loading为假,即。
    • 谢谢。。这就是问题所在。
    猜你喜欢
    • 2014-11-29
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2014-03-15
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多