S
S
Samat2021-10-04 08:46:30
JSON Web Token
Samat, 2021-10-04 08:46:30

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;
  }
}

jwt.strategy.ts
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 };
  }
}

decorator
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,
    };
  },
);

resolver
@Query(() => [User])
  @UseGuards(GqlAuthGuard)
  async findAllUsers() {
    try {
      return await this.userService.findAll();
    } catch (error) {
      console.error(error);
    }
  }


Any protected GqlAuthGuard always returns UNAUTHENTICATED, why is that?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question