【发布时间】:2020-06-27 12:17:40
【问题描述】:
您好,我是 GraphQl 和 Apollo Server 的新手。 我想对我的项目实施身份验证。
但是
由于某种原因,我似乎无法在阿波罗服务器中的解析器上设置上下文。
这是我的索引
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
const userId = jwtDecode(req.headers.authorization)
return userId.sub
}
})
还有我的查询
Query: {
users: async (parent, args, context) => {
try {
console.log(context)
return await getUsers(context)
} catch (err) {
console.log(err)
throw new Error(err.message)
}
}
When I try to output the context the result is always like this...
{ injector:
Injector {
options:
{ name: 'index.ts_8346047369535445_SESSION',
injectorScope: 'SESSION',
hooks: [Array],
children: [] },
_classMap: Map {},
_factoryMap: Map {},
_applicationScopeInstanceMap:
Map {
Symbol(ModuleConfig.index.ts_8346047369535445) => undefined,
[Function] => undefined },
_sessionScopeInstanceMap: Map { [Function: ModuleSessionInfo] => [ModuleSessionInfo] },
_applicationScopeServiceIdentifiers:
[ Symbol(ModuleConfig.index.ts_8346047369535445), [Function] ],
_requestScopeServiceIdentifiers: [],
_sessionScopeServiceIdentifiers: [ [Function: ModuleSessionInfo] ],
_hookServiceIdentifiersMap: Map {},
_name: 'index.ts_8346047369535445_SESSION',
_injectorScope: 'SESSION',
_defaultProviderScope: 'SESSION',
........
【问题讨论】:
-
可以在
jwtDecode方法中添加代码吗? -
您好!我只是在 npm 上使用 jwt-decode 模块
-
userId持有什么?你可以控制台记录它并检查它打印的内容吗?我认为您正在解码的req.headers.authorization(令牌)可能有问题。 -
这是解码后的令牌 { iss: 'test-api.auth0.com', sub: 'wNfr5wYesnNYSUGObOP6l64FzdMrSulB@clients', aud: 'test-api.auth0.com/api/v2', iat: 1584351388, exp: 15844378, azp:78 'wNfr5wYesnNYSUGObOP6l64FzdMrSulB',范围:'read:client_grants....
-
试图返回一个字符串作为上下文,仍然是同样的错误。
标签: graphql apollo graphql-js apollo-server graphql-modules