0
votes

Hello I'm new to GraphQl and to Apollo Server. I would like to implement authentication on my project.

But

For some reason, I can't seem to set context on my resolvers in apollo server.

Here's my index

    const server = new ApolloServer({ 
        typeDefs, 
        resolvers, 
        context: ({ req }) => {
           const userId = jwtDecode(req.headers.authorization)
           return userId.sub
        }
    })

And my query

    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',
........

1
can you add the code to jwtDecode method?Hemanath
Hello! I'm just using the jwt-decode module on npmDwight Ferrer
what does userId holds? can you console log it and check what it prints? I think there might be a problem with the req.headers.authorization (token) you are decoding.Hemanath
Here's the decoded token { iss: 'test-api.auth0.com', sub: 'wNfr5wYesnNYSUGObOP6l64FzdMrSulB@clients', aud: 'test-api.auth0.com/api/v2', iat: 1584351388, exp: 1584437788, azp: 'wNfr5wYesnNYSUGObOP6l64FzdMrSulB', scope: 'read:client_grants....Dwight Ferrer
Tried to returning a string for the context, still the same error.Dwight Ferrer

1 Answers

1
votes

What's returned inside the context function should always be an object. So you would do something like

context: ({ req }) => {
  const { sub } = jwtDecode(req.headers.authorization)
  return {
    sub,
  }
}

and then access the value inside the resolver by calling context.sub.

However, if you're using GraphQL Modules to create your schema, you should follow the library's documentation for configuring your context on a per-module basis.