Str*_*ch0 4 node.js jwt graphql graphql-js apollo-server
我有一个由 JWT 授权的 graphql 端点。我的 JWT 策略验证 JWT,然后将用户对象添加到请求对象。
在宁静的路线中,我会像这样访问我的用户数据:
router.get('/', (req, res, next) => {
console.log('user', req.user)
}
Run Code Online (Sandbox Code Playgroud)
我想在我的 graphql 解析器中访问 req.user 对象以提取用户的 ID。但是,当我尝试记录context
变量时,它始终为空。
我是否需要配置我的 graphql 端点以将req
数据传递给解析器?
我的 app.js 有我的 graphql 设置如下:
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
app.use('/graphql', [passport.authenticate('jwt', { session: false }), bodyParser.json()], graphqlExpress({ schema }));
Run Code Online (Sandbox Code Playgroud)
然后我有我的解析器:
const resolvers = {
Query: {
user: async (obj, {email}, context) => {
console.log('obj', obj) // undefined
console.log('email', email) // currently passed through in graphql query but I want to replace this with the user data passed in req / context
console.log('context', context) // {}
return await UserService.findOne(email)
},
};
// Put together a schema
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
Run Code Online (Sandbox Code Playgroud)
如何在我的解析器中访问我的 JWT 用户数据?
显然,您需要像这样手动传递上下文:
app.use('/graphql', [auth_middleware, bodyParser.json()], (req, res) => graphqlExpress({ schema, context: req.user })(req, res) );
Run Code Online (Sandbox Code Playgroud)
如果有人感兴趣,可以在这里找到答案:
归档时间: |
|
查看次数: |
10127 次 |
最近记录: |