[ ] 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.
executionContext.switchToHttp().getRequest()
inside Guard return null, when I hit resolver using Graphiql (GraphQL IDE)
executionContext.switchToHttp().getRequest()
should return http request data
@Injectable()
export class RolesGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
try {
const request = context.switchToHttp().getRequest();
Nest version: 5.3.6
For Tooling issues:
- Node version: v10.9.0
- Platform: MAC
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.