首页 > 解决方案 > nestjs:从jwt获取当前连接的用户

问题描述

我在 Nest js 中创建了身份验证护照 jwt 系统,一切正常,但我无法从请求中提取当前用户

这是我的策略

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
     private userService:UserService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey:"MedAKRAOU",
    });
  }

  async validate(payload:PayLoadInterface) {
      
      if(payload){
          console.log(payload);
          return payload;
      }

    else throw new UnauthorizedException()
  }
}

它可以工作并打印我放入有效负载的所有信息

这是 AuthGuards:

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

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

在我使用卫兵的另一个控制器中

@Post()
    @UseGuards(JwtAuthGuard)
   async addCv(@Body() cv:CvDto,@Request() req):Promise<CvEntity>{
     console.log("user extra from req"+req.user)
    return await this.cvServise.addCv(cv)
    }

它打印:来自 req[object Object] 的用户额外请帮我找到解决方案

标签: nestjs-jwt

解决方案


推荐阅读