如何使用 NestJS 操作 Passport-JS AuthGuard 中的 cookie?

yah*_*rga 6 passport.js nestjs

因此,我正常设置了 Local 和 JWT 策略,它们运行得非常好。我通过登录路由设置 JWT cookie。我还想设置刷新 cookie 令牌,然后能够通过 JWT AuthGuard 删除和重置 JWT 令牌,手动刷新它并将标志设置ignoreExpiration为 true。

我希望能够通过 JWT AuthGuard 操作 cookie。我已经可以查看它们,但似乎无法设置它们。有没有办法能够做到这一点?

/************************
 * 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

yah*_*rga 1

根据Passport JWT Guard 配置文档,我们可以设置要传递给回调的请求,以便我们可以使用该validate方法来控制它(此选项也适用于其他策略)。完成后,您可以根据 Express(或 Fastify)查看如何操作 cookie。

对于 Express(我正在使用的),可以在文档中找到该方法: