nestjs 使用AuthGuard 设置全局守卫
时间: 2023-07-22 22:44:16 浏览: 71
要在 NestJS 中使用 `AuthGuard` 设置全局守卫,可以按照以下步骤操作:
1. 创建一个名为 `auth.guard.ts` 的文件,并将以下代码复制到该文件中:
```typescript
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
```
这将创建一个名为 `JwtAuthGuard` 的类,该类将扩展 NestJS 中的 `AuthGuard` 类,并将 `jwt` 作为参数传递给 `AuthGuard` 构造函数。
2. 在 `app.module.ts` 文件中导入 `JwtAuthGuard` 类,并将其添加到 `providers` 数组中:
```typescript
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { JwtAuthGuard } from './auth.guard';
@Module({
providers: [
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
],
})
export class AppModule {}
```
这将在整个应用程序中使用 `JwtAuthGuard` 作为全局守卫。
现在,每当用户尝试访问需要身份验证的端点时,`JwtAuthGuard` 将被调用,以确保用户已通过身份验证。