nestjs 中@UseGuards(AuthGuard()) AuthGuard的参数 如何获得
时间: 2024-03-17 12:42:02 浏览: 19
在 NestJS 中,`@UseGuards(AuthGuard())` 中的 `AuthGuard()` 实际上是一个 passport.js 的策略,用于处理用户身份验证。在使用 `AuthGuard()` 时,我们可以通过参数来指定使用的策略名称或者配置选项。
以下是一些常用的 `AuthGuard()` 的参数:
- 策略名称:如果我们在使用 `passport.js` 时定义了多个策略,我们可以通过指定策略名称来确定使用哪个策略。例如:
```typescript
@UseGuards(AuthGuard('jwt'))
```
- 配置选项:我们也可以通过配置选项来定制 `AuthGuard()` 的行为。例如:
```typescript
@UseGuards(AuthGuard({
passportOptions: { session: false },
authInfo: true,
// ... 其他配置选项
}))
```
其中,`passportOptions` 用于指定 `passport.js` 的选项,`authInfo` 用于指定是否将 `authInfo` 传递给路由处理器函数(默认为 `false`)。
需要注意的是,不同的 `AuthGuard()` 有不同的配置选项,具体的配置选项可以参考官方文档。此外,我们也可以自定义 `AuthGuard()` 的行为,具体的做法是继承 `AuthGuard()` 并覆盖其中的方法。
以下是一个自定义 `AuthGuard()` 的示例代码:
```typescript
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class CustomAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
// 在这里覆盖 AuthGuard 的逻辑
return true;
}
}
```
使用自定义的 `AuthGuard()` 时,我们只需要在需要认证的路由上使用 `@UseGuards(CustomAuthGuard)` 装饰器即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)