Nestjs如何将数据从AuthGuard传递到控制器

Kri*_*rga 1 security authentication api node.js nestjs

我有两个微服务,一个用于身份验证,另一个用于用户。我可以登录并获取令牌,并且仅在登录时才能使用受保护的路由。但是我想使用在 AuthGuard 的 canActivate 函数中获得的 userId,但我无法在控制器中访问它。最好的方法是什么?

我的授权守卫:

import { CanActivate, ExecutionContext, Inject, Logger } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';

export class JwtAuthGuard implements CanActivate {
  constructor(
    @Inject('AUTH_CLIENT')
    private readonly client: ClientProxy,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();

    try {
      const res = await this.client
        .send(
          { role: 'auth', cmd: 'check' },
          { jwt: req.headers['authorization']?.split(' ')[1] },
        )
        .toPromise<boolean>();

      return res;
    } catch (err) {
      Logger.error(err);
      return false;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

  @UseGuards(JwtAuthGuard)
  @Get('greet')
  async greet(@Request() req): Promise<string> {
    return 'AUTHENTICATED!' + req;
  }
Run Code Online (Sandbox Code Playgroud)

响应:

AUTHENTICATED![object Object]
Run Code Online (Sandbox Code Playgroud)

Abb*_*bah 5

userId将您在 AuthGuard 中获得的附加到该req对象,然后您可以在控制器中访问它:

// after fetching the auth user in the AuthGuard, attach its ID like this
req.userId = authUser.id
Run Code Online (Sandbox Code Playgroud)

在控制器中,您可以像这样访问它:

@UseGuards(JwtAuthGuard)
@Get('greet')
async greet(@Request() req): Promise<string> {
  return 'AUTHENTICATED USER ID!' + req.userId;
}
Run Code Online (Sandbox Code Playgroud)