Answer the question
In order to leave comments, you need to log in
Why doesn't AuthGuard work in nest(fastify) + Graphql + jwt?
user.guard.ts
import { Injectable, ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
}
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'reallyfuckinghard',
});
}
async validate(payload: any) {
const { _id, email } = payload;
return { _id, email };
}
}
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
export const CurrentUser = createParamDecorator(
(data: unknown, context: ExecutionContext) => {
console.log(GqlExecutionContext.create(context).getContext().req.user);
const { _id, email } =
GqlExecutionContext.create(context).getContext().req.user;
return {
_id,
email,
};
},
);
@Query(() => [User])
@UseGuards(GqlAuthGuard)
async findAllUsers() {
try {
return await this.userService.findAll();
} catch (error) {
console.error(error);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question