H
H
Helios692021-01-31 14:57:55
Express.js
Helios69, 2021-01-31 14:57:55

How to use cookies in NestJS?

There is such an endpoint for getting a list of books, only for an authorized user.

@Get()
  @Roles(Role.Admin, Role.User)
  @UseGuards(JwtAuthGuard, RolesGuard)
  getAllBooks(): Promise<Book[]> {
    return this.bookService.getAllBooks();
  }


From the frontend I make a Get-request, while being authorized. Cookies come to the back, but 401 code comes. Through Postman, I simply copied the token from the cookies and inserted its Bearer token field and everything worked out. Question: how to get a token from cookies on the back and use it?

Guard code, if needed:
JWTAuthGuard
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

RolesGuard
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    @Inject(forwardRef(() => UserService))
    private userService: UserService,
    private reflector: Reflector,
  ) {}

  canActivate(context: ExecutionContext): Promise<boolean> | boolean {
    const request = context.switchToHttp().getRequest();
    console.log(request);

    const { userId } = request.user;
    const requiredRoles = this.reflector.getAllAndOverride<Role[]>('roles', [
      context.getHandler(),
      context.getClass(),
    ]);
    const hasRole = async (userId: number, requiredRoles: Role[]) => {
      const { role } = await this.userService.getById(userId);

      return requiredRoles.includes(role) || !requiredRoles;
    };

    return hasRole(userId, requiredRoles);
  }
}


Z.Y. Cookies-Parser is worth it, cookies come through the request, but apparently they are not checked in guards. Everything works with the commented Guards, it comes to cookies normally.
How do I get cookies
@Get()
  // @Roles(Role.Admin, Role.User)
  // @UseGuards(JwtAuthGuard, RolesGuard)
  getAllBooks(@Cookies() cookies: string): Promise<Book[]> | string {
    return cookies;
  }

Z.Y.S. Perhaps the matter is that I use JWT Strategy. But I don't quite understand how to change it to Cookie.
JWT Strategy
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { TokenPayload } from '../token-payload.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.JWT_SECRET,
    });
  }

  async validate(payload: TokenPayload) {
    return { userId: payload.userId };
  }
}

JwtGuard
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

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