nestjs 守卫使用

175 阅读2分钟

这篇文章介绍了在 NestJS 中的 Guards(守卫),并提供了实际的例子以帮助理解如何在应用程序中使用守卫。

Guard 是 NestJS 中的中间件,可以拦截进入路由器的请求,并在传递给处理程序之前进行身份验证和授权。Guard 可以访问请求和响应对象,并可以使用它们来过滤进入应用程序的请求。

下面是一个示例,展示如何创建和使用 Guard:

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    // 在这里编写身份验证逻辑
    return true; // 如果身份验证通过,返回 true
  }
}

在这个例子中,AuthGuard 类是一个实现 CanActivate 接口的 Injectable 类。CanActivate 是 NestJS 中的一个接口,用于定义 Guard 的行为。

AuthGuard 类的 canActivate 方法接收一个 ExecutionContext 对象,该对象提供了访问请求和响应对象的方法。在该方法中,你可以编写身份验证逻辑,并根据验证的结果返回 true 或 false。如果返回 true,请求将被传递给处理程序,否则将不会。

在 NestJS 应用程序中,你可以将 Guard 设置为全局或局部。全局设置会应用于整个应用程序,而局部设置只适用于指定的路由或端点。下面是一个局部设置的例子:

@Controller('cats')
export class CatsController {
  @Get()
  @UseGuards(AuthGuard)
  async findAll(): Promise<Cat[]> {
    // 在这里编写返回所有 Cat 对象的逻辑
  }
}

在这个例子中,AuthGuard 守卫被应用于 GET /cats 端点,并且只有通过身份验证的用户才能访问该端点。通过使用 @UseGuards 装饰器来指定要使用的 Guard。

在 NestJS 中还有许多其他类型的 Guard,例如:

  • Authentication Guards:用于身份验证和登录。
  • Role Guards:用于检查用户角色。
  • Jwt Guards:用于解析和验证 JSON Web Token。
  • Throttler Guards:用于限制 API 的访问速率。

通过在 NestJS 应用程序中使用 Guard,可以提高应用程序的安全性和可靠性,同时可以限制对敏感数据的访问。

可参考: nestjs实现图形校验+单点登录 - 掘金 (juejin.cn)