首页 > 解决方案 > 在 NestJs 中何时使用守卫以及何时使用中间件

问题描述

我想创建一个 NestJs 应用程序,并希望有一个中间件验证请求对象中的令牌,以及一个身份验证保护来验证令牌有效负载中的用户。

通过拆分这个,我希望有一个干净的分离。首先我的中间件

@Injectable()
export class TokenMiddleware implements NestMiddleware {
  use(req: any, res: Response, next: NextFunction) {
    try {
      const headers: IncomingHttpHeaders = req.headers;
      const authorization: string = headers.authorization;
      const bearerToken: string[] = authorization.split(' ');
      const token: string = bearerToken[1];

      // !! Check if token was invalidated !!

      req.token = token;
      req.tokenPayload = verifyToken(token);
      next();
    } catch (error) {
      throw new UnauthorizedException();
    }
  }
}

它仅验证令牌并使用编码令牌及其有效负载扩展请求对象。我的授权守卫

@Injectable()
export class AuthenticationGuard implements CanActivate {
  constructor(private readonly usersService: UsersService) {}

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

    try {
      const user: any = request.tokenPayload;

      if (!user) {
        throw new Error();
      }

      const findByIdDTO: FindByIdDTO = { id: user.id };
      const existingUser: UserRO = await this.usersService.findById(findByIdDTO);

      if (!existingUser) {
        throw new Error();
      }

      // attach the user to the request object?

      return true;
    } catch (error) {
      throw new UnauthorizedException();
    }
  }
}

该守卫检查令牌有效负载中提供的用户是否是有效用户。如果一切正常,我应该在哪里将用户附加到请求对象?据我所知,警卫只检查某事是否正确。但我不想将所有这些逻辑保留在令牌中间件中。在 auth guard 中完成验证后,我可以在哪里将数据库用户附加到请求中?

标签: javascriptnode.jstypescriptexpressnestjs

解决方案


如果你想做类似于 Passport 的事情,你总是可以将用户附加到req.user,这在 Node.JS 世界中被视为非常标准的设置。

对你的一个附带问题:有什么理由不让两个守卫一个接一个地发挥作用?让一名警卫检查令牌是否存在并且确实是有效的令牌,而一名用于验证令牌上的用户确实是有效的。这样你就不用使用中间件(主要是为了兼容性而包括在内)并且仍然有分离的逻辑。


推荐阅读