我这样做的方式是,我什至会在 graphql 服务器之前构建 auth 中间件,因为有时需要在其他中间件中获取有关经过身份验证的用户的信息,而不仅仅是 GraphQL 模式。将添加一些代码,您需要完成它
const auth = (req, res, next) => {
if (typeof req.headers.authorization !== 'string') {
return next();
}
const header = req.headers.authorization;
const token = header.replace('Bearer ', '');
try {
const jwtData = jwt.verify(token, JWT_SECRET);
if (jwtData && jwtData.user) {
req.user = jwtData.user;
} else {
console.log('Token was not authorized');
}
} catch (err) {
console.log('Invalid token');
}
return next();
};
如果设置了正确的令牌,我会将用户注入每个请求。然后在 apollo server 2 中,您可以按如下方式进行操作。
const initGraphQLserver = () => {
const graphQLConfig = {
context: ({ req, res }) => ({
user: req.user,
}),
rootValue: {},
schema,
};
const apolloServer = new ApolloServer(graphQLConfig);
return apolloServer;
};
此函数将启动 ApolloServer,您将在正确的位置应用此中间件。申请 apollo server 2 之前我们需要有 auth 中间件
app.use(auth);
initGraphQLserver().applyMiddleware({ app });
假设应用是
const app = express();
现在您将把用户 jwtData 中的用户作为“用户”注入到每个解析器的上下文中,或者在其他中间件中的 req.user 中,您可以像这样使用它。这是我询问哪个用户已通过身份验证的问题
me: {
type: User,
resolve: async (source, args, ctx) => {
const id = get(ctx, 'user.id');
if (!id) return null;
const oneUser = await getOneUser({}, { id, isActive: true });
return oneUser;
},
},
我希望即使使用分段代码,一切都有意义。随时问任何问题。肯定有更复杂的身份验证,但这个基本示例通常对于简单的应用程序来说已经足够了。
最好的大卫