NestJS中使用Guard实现路由保护

NestJS中Guard是一种用于保护路由的机制。它可以在路由处理之前执行一些逻辑,例如验证用户身份、检查权限等。

什么是Guard?

Guard是一个实现了CanActivate接口的类。它可以在路由处理之前执行一些逻辑,例如验证用户身份、检查权限等。如果Guard返回true,则路由处理将继续执行。如果Guard返回false,则路由处理将被中止,并返回一个错误响应。

如何创建Guard?

要创建一个Guard,需要创建一个实现了CanActivate接口的类。

typescript 复制代码
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> {
    const request = context.switchToHttp().getRequest();
    console.log(request.headers);
    console.log(request.query);
    console.log(request.params);
    // 添加逻辑验证用户身份、检查权限等。
    // 比如从request中获取user或token,然后验证user或token是否有效。
    return true;
  }
}

这里创建了一个名为AuthGuard的类,它实现了CanActivate接口。在canActivate方法中可以添加逻辑,例如验证用户身份、检查权限等。这个例子中只是简单地返回true,表示路由处理可以继续执行。

如何使用Guard?

要使用Guard,需要在模块的providers数组中注册它,并在需要使用它的路由处理器或控制器上添加@UseGuards装饰器。

typescript 复制代码
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from './auth.guard';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_GUARD,
      useClass: AuthGuard,
    },
  ],
})
export class AppModule {}

这里在AppModule中注册了AuthGuard,并将其作为全局Guard使用。这意味着AuthGuard将应用于所有路由处理器和控制器。

另外也可以在特定的路由处理器或控制器上使用@UseGuards装饰器来应用Guard。

typescript 复制代码
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from './auth.guard';

@Controller()
@UseGuards(AuthGuard)
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

这里在AppController上使用了@UseGuards装饰器来应用AuthGuard。这意味着AuthGuard将只应用于AppController中的路由处理器。

此时访问这个路由地址就会得到如下结果

json 复制代码
{
  "message":"Forbidden resource",
  "error":"Forbidden",
  "statusCode":403
}

总结

Guard是NestJS中一个非常强大的工具,可以用于保护路由。通过创建一个实现了CanActivate接口的类,并在需要使用它的路由处理器或控制器上添加@UseGuards装饰器就可以轻松地使用Guard。

相关推荐
Mr_li3 天前
NestJS 集成 TypeORM 的最优解
node.js·nestjs
前端付豪4 天前
Nest 项目小实践之注册登陆
前端·node.js·nestjs
Mr_li4 天前
手摸手,教你如何优雅的书写 NestJS 服务配置
node.js·nestjs
Jiude5 天前
AI 全栈时代的工程化护栏:Vben-Nest 让 Mock 契约落地成真实后端
前端·后端·nestjs
折七6 天前
NestJS 用了两年,我换了这个
typescript·node.js·nestjs
NEXT0613 天前
深度解析 JWT:从 RFC 原理到 NestJS 实战与架构权衡
前端·typescript·nestjs
明月_清风15 天前
从“搬运工”到“指挥官”:通过 IoC 容器重塑你的后端思维
后端·nestjs
UIUV16 天前
实现RAG功能学习笔记
react.js·langchain·nestjs
None32120 天前
【NestJs】如何使用Prisma实现@Transactional装饰器开启事务并且跨Service传递
nestjs
前端付豪21 天前
Express 如何使用 multer 文件上传?
前端·node.js·nestjs