Secure GraphQL queries with express js, passport s

穿精又带淫゛_ 提交于 2020-08-21 06:55:41

问题


I have started using graphql in my express js project but i am wondering how to protect some of my GraphQL query. Previously i used passport js(JWT) for this and that works great. It was really easy to secure route but with graphql(express-graphql) i couldn't find any solution. Furthermore it will be nice to have some kind of role based solution to protect particular fields. Is there any good tutorial how to secure graphQL ?


回答1:


Last I checked there weren't any really good tutorials out there that show how to secure a GraphQL endpoint. However, the consensus in the community (GraphQL and Apollo slack channels) is that it's best to do Authentication separate from GraphQL (eg. using Passport) and do authorization in your resolve functions, possibly by decorating them with some role-based auth.

The best link I can provide at the moment is this post I wrote a while ago about setting up Authentication for a GraphQL endpoint with Passport.js. I hope it helps!

I'm currently working on a Full-stack GraphQL tutorial for React + Node.js with Apollo for which I'm planning to do a part about Auth. I'll try to update this answer as soon as I've published it.




回答2:


I'm currently evaluating the potential of authorization over resolvers with express, passport and jwt. It's not fully tested, but it works.

For this to work, you need to pass at least the request in the context:

const graphql = graphqlExpress((req, res) => {
  return ({
    schema,
    rootValue: resolver,
    // For query authorization. Ideally, Passport will handle all requests and authenticate
    // each one for the current user. The queries will fetch data exclusively related to that user.
    context: { req, res },
  });
});
// The api
app.use('/api', graphql);

In this case I promisified the passport authentication:

const auth = (req, res) => new Promise((resolve, reject) => {
  passport.authenticate('jwt', { session: false }, (err, user) => {
    if (err) reject(err);
    if (user) resolve(user);
    else reject('Unauthorized');
  })(req, res);
});

const resolver = {
  users: (root, ctx) => auth(ctx.req, ctx.res)
    .then(() => User.find({}, (err, res) => res))
    .catch((err) => {
      throw new Error(err);
    }),
};

Since there's not that many examples on how to cover this, I've struggled to make it simple, but I think I did it well.

Here are the resources I used to get to this point:

  • how to get passport.authenticate local strategy working with async/await pattern
  • https://matoski.com/article/jwt-express-node-mongoose/
  • https://dev-blog.apollodata.com/auth-in-graphql-part-2-c6441bcc4302


来源:https://stackoverflow.com/questions/42885983/secure-graphql-queries-with-express-js-passport-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!