Search code examples
passport.jsnestjs

How to manipulate cookies in Passport-JS AuthGuard with NestJS?


So, I set up the Local and JWT strategies normally, and they work wonderfully. I set the JWT cookie through the login route. I want to also set the refresh cookie token, and then be able to remove and reset the JWT token through the JWT AuthGuard, refreshing it manually and setting the ignoreExpiration flag to true.

I want to be able to manipulate the cookies through the JWT AuthGuard. I can already view them, but I can't seem to set them. Is there a way to be able to do this?

/************************
 * auth.controller.ts
 ************************/
import { Controller, Request, Get, Post, UseGuards } from '@nestjs/common';
import { AuthGuard }                                 from '@nestjs/passport';
import { AuthService }                from './auth/auth.service';
import { SetCookies, CookieSettings } from '@ivorpad/nestjs-cookies-fastify';
import { ConfigService }              from '@nestjs/config';


@Controller('auth')
export class AuthController {
    constructor(
        private readonly authService: AuthService,
        private readonly configService: ConfigService,
    ) {}

    @UseGuards(AuthGuard('local'))
    @Post('login')
    @SetCookies()
    async login(@Request() request) {
        const jwtCookieSettings = this.configService.get<CookieSettings>('shared.auth.jwtCookieSettings');
        request._cookies = [{
            name   : jwtCookieSettings.name,
            value  : await this.authService.signJWT(request.user),
            options: jwtCookieSettings.options,
        }];
    }


    @UseGuards(AuthGuard('jwt'))
    @Get('profile')
    async getProfile(@Request() req) {
        return req.user;
    }
}

/************************
 * jwt.strategy.ts
 ************************/
import { Strategy, StrategyOptions } from 'passport-jwt';
import { PassportStrategy }          from '@nestjs/passport';
import { Injectable, Request }       from '@nestjs/common';
import { ConfigService }             from '@nestjs/config';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(private readonly configService: ConfigService) {
        super(configService.get<StrategyOptions>('shared.auth.strategy.jwt.strategyOptions'));
    }
    
    async validate(@Request() request, payload: any) {
        return payload;
    }
}

Solution

  • According to the Passport JWT Guard Configuration Docs, we can set the request to be passed to the callback, so that we may be able to control it using the validate method (this option is available with other strategies, too). Once that is done, you may view how to manipulate the cookies, as per Express (or Fastify).

    For Express (which is what I am using), the method can be found in the docs: