【问题标题】:Apollo Server 2 + Auth0阿波罗服务器 2 + Auth0
【发布时间】:2019-02-08 01:00:08
【问题描述】:

所以我有一个应用程序通过 Auth0 登录并将 jwt 令牌保存在 cookie 中。

我还有一个检索数据的 Apollo Server 2。如何保护 Apollo Server 并仅在用户登录并通过 Auth0 服务器验证时才返回数据?

下面的代码直接来自https://www.apollographql.com,但我不明白的是如何处理下面的getUser(token),以实际检查授权标头中的有效JWT,如果存在,用户将被允许访问受保护的资源?

// using apollo-server 2.x
const { ApolloServer } = require('apollo-server');

const server = new ApolloServer({
 typeDefs,
 resolvers,
 context: ({ req }) => {
   // get the user token from the headers
   const token = req.headers.authorization || '';

   // try to retrieve a user with the token
   const user = getUser(token);

   // add the user to the context
   return { user };
 },
});

server.listen().then(({ url }) => {
 console.log(`???? Server ready at ${url}`)
});

【问题讨论】:

    标签: node.js graphql auth0 apollo apollo-server


    【解决方案1】:

    getUser 是使用给定令牌返回用户的方法。您可能需要自己编写该方法或使用 OAuth 的 getUser 方法。

    获取用户对象后,您将返回它,因此现在您可以访问解析器中的用户对象。在您的解析器方法中,第三个参数是您的上下文对象。您可以在那里访问用户对象。如果您想保护该解析器只允许登录用户使用,如果用户为空或未定义,您可以抛出错误。

    例如:

    export const resolvers = {
    Query: {
      Me: (parent, args, { user }) => {
        if (!user) return Error(`Not Logged In!`)
        return user
      }
     }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 2020-10-04
      • 2020-10-18
      • 2019-03-06
      • 2021-10-28
      • 2021-02-13
      • 1970-01-01
      • 2020-07-19
      • 2019-09-15
      相关资源
      最近更新 更多