You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS中使用fastify适配器与StrategyCreatedStatic时无法访问用户对象

解决NestJS + Fastify环境下Passport认证用户无法通过req.user访问的问题

核心原因

Fastify适配器下,NestJS封装的FastifyRequest并非原生Fastify请求对象,Passport默认会将认证后的用户信息挂载到原生Fastify请求的user字段上,而不是NestJS封装的FastifyRequest直接属性。


解决方案

方法1:使用NestJS内置@User()装饰器(推荐)

NestJS提供了专门的@User()装饰器,无需关心底层请求对象结构,直接获取认证用户:

import { Controller, Get, UseGuards, User } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('protected')
export class ProtectedController {
  @Get()
  @UseGuards(AuthGuard('myguard'))
  getProtectedData(@User() user: YourUserType) { // 替换为你的用户实体类型
    return { 
      user, 
      message: '已成功获取认证用户信息' 
    };
  }
}

方法2:通过FastifyRequest.raw访问原生请求

如果必须使用@Req()装饰器,需通过raw属性获取原生Fastify请求,再取用户信息:

import { Controller, Get, UseGuards, Req } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { FastifyRequest } from '@nestjs/platform-fastify';

@Controller('protected')
export class ProtectedController {
  @Get()
  @UseGuards(AuthGuard('myguard'))
  getProtectedData(@Req() req: FastifyRequest) {
    const user = req.raw.user; // 从原生Fastify请求中提取用户
    return { 
      user, 
      message: '已成功获取认证用户信息' 
    };
  }
}

自定义策略的注意事项

确保你的自定义策略实现正确,validate方法需要返回用户对象(即使调用了this.success),NestJS的Passport适配器依赖此返回值完成用户信息挂载:

import { Strategy } from 'passport-custom';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyGuardStrategy extends PassportStrategy(Strategy, 'myguard') {
  constructor() {
    super();
  }

  async validate(req: any) {
    // 这里编写你的自定义认证逻辑(比如校验请求头、参数等)
    const authenticatedUser = { id: 1, username: 'test_user' }; // 示例认证用户

    this.success(authenticatedUser, { authMessage: '认证通过' });
    return authenticatedUser; // 必须返回用户对象,否则无法正确挂载
  }
}

模块注册验证

确保在模块中正确注册Passport和自定义策略:

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { MyGuardStrategy } from './my-guard.strategy';
import { ProtectedController } from './protected.controller';

@Module({
  imports: [PassportModule],
  providers: [MyGuardStrategy],
  controllers: [ProtectedController],
})
export class AuthModule {}

内容的提问来源于stack exchange,提问作者Yetispapa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 11:33:24