Nest: Resolver Guards: Cannot get request data from ExecutionContext

Created on 12 Sep 2018  路  7Comments  路  Source: nestjs/nest

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior


executionContext.switchToHttp().getRequest()
inside Guard return null, when I hit resolver using Graphiql (GraphQL IDE)

Expected behavior


executionContext.switchToHttp().getRequest() should return http request data

Minimal reproduction of the problem with instructions

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    try {
      const request = context.switchToHttp().getRequest();

Environment


Nest version: 5.3.6

For Tooling issues:

  • Node version: v10.9.0
  • Platform: MAC

All 7 comments

I found a workaround for this issue, but I don't like it

Step 1: Put your request data in graphql context

GraphQLModule.forRoot({
      resolvers: { JSON: GraphQlJSON },
      typeDefs: schema,
      debug: true,
      playground: true,
      installSubscriptionHandlers: true,
      tracing: true,
      context: ({ req }) => ({
        authScope: req.headers.authorization,
      }),
    }),

Step 2: Get context data, in this case authScope, in your guard

async canActivate(context: ExecutionContext): Promise<boolean> {
   ...
   lodash.find(context.getArgs(), 'authScope')
   ...
}

See https://docs.nestjs.com/graphql/tooling "Execution Context"

@kamilmysliwiec I'm struggling with these changes finding the best way to be able to retrieve the underlying HTTP Request object (which holds the user object I need to be able to validate against). I've tried following your instructions for GqlExecutionContext.create() but no matter what getRequest() still returns undefined. At this point I have to manually inject the req.user using the technique @sofyanhadia has shown above.

@WonderPanda see https://docs.nestjs.com/techniques/authentication GraphQL (there is an example how to achieve that)

Thanks @kamilmysliwiec it seems like the manually injecting the req through the GQL context is the correct approach

While closed, the documentation isn't great. There is nothing the explains what you'll get back from getContext() of a GqlExecutionContext.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

artaommahe picture artaommahe  路  3Comments

breitsmiley picture breitsmiley  路  3Comments

tronginc picture tronginc  路  3Comments

cdiaz picture cdiaz  路  3Comments

rafal-rudnicki picture rafal-rudnicki  路  3Comments