Microservices

守卫

学习如何在 NestJS 微服务中使用守卫进行身份验证和授权

守卫

微服务守卫和常规 HTTP 应用程序守卫之间没有根本区别。唯一的区别是,您应该使用 RpcException 而不是抛出 HttpException

提示 RpcException 类从 @nestjs/microservices 包导出。

绑定守卫

以下示例使用方法作用域守卫。就像基于 HTTP 的应用程序一样,您也可以使用控制器作用域守卫(即,在控制器类前加上 @UseGuards() 装饰器)。

@@filename()
@UseGuards(AuthGuard)
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): number {
  return (data || []).reduce((a, b) => a + b);
}
@@switch
@UseGuards(AuthGuard)
@MessagePattern({ cmd: 'sum' })
accumulate(data) {
  return (data || []).reduce((a, b) => a + b);
}