【问题标题】:Nestjs how to pass data from AuthGuard to controllerNestjs如何将数据从AuthGuard传递到控制器
【发布时间】:2021-08-31 21:49:02
【问题描述】:

我有两个微服务,一个用于身份验证,另一个用于用户。我可以登录并获取令牌,并且只有在登录时才能使用受保护的路由。但是我想使用在 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;
    }
  }
}

控制器:

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

回应:

AUTHENTICATED![object Object]

【问题讨论】:

    标签: node.js api security authentication nestjs


    【解决方案1】:

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

    // after fetching the auth user in the AuthGuard, attach its ID like this
    req.userId = authUser.id
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 2020-03-02
      • 2017-03-23
      • 2019-07-26
      • 2020-05-29
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多