使用Passport验证graphcool-yoga

时间:2018-04-27 07:39:03

标签: authentication passport.js graphql-js graphcool prisma

我正在使用graphcool-yoga和prisma绑定项目。想要使用护照的Local,Bearer,Github和Twitter策略设置身份验证。这是我的graphql查询的样子

user: (root, args, context, info) => {
const { id } = args;
if(!passport.authenticate('bearer')(context)){
    throw new Error('Not Authorised');
}
if (!id) {
  throw new Error('Id cannot be empty');
}

return context.db.query.user(
  {
    where: {
      id: id,
      active: true,
    },
  },
  info,
);}

我的auth.js,我已经实施了持票人令牌的护照策略:

import express from 'express';
import passport from 'passport';
import { Strategy as BearerStrategy } from 'passport-http-bearer';
import jwt from 'jsonwebtoken';

passport.use(new BearerStrategy((token, done) => {
    jwt.verify(token, process.env.JWT_SECRET, function(err, decoded) {
        if (err) return done(null, err);
        if (decoded.sub) {
            done(null, decoded.sub || undefined);
        }
    });
}));
const middleware = express();
middleware.use(passport.initialize());
middleware.use(passport.session());
module.exports = {
    authMiddleware: middleware
};

最后我将它用作中间件:

const server = new GraphQLServer({
  typeDefs: 'app/schema.graphql', // application api schema
  resolvers,
  context: req => ({
    ...req,
    db
  }),
});
server.express.use(authMiddleware);

这是我在阅读各种来源后可以写的但是没有用。任何正确和最好的方法吗?

0 个答案:

没有答案