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。

相关推荐
irving同学462384 天前
TypeORM 列装饰器完整总结
前端·后端·nestjs
Wang's Blog5 天前
Nestjs框架: 基于策略的权限控制(ACL)与数据权限设计
nestjs·rbac·acl
三十_5 天前
【NestJS】构建可复用的数据存储模块 - 动态模块
前端·后端·nestjs
SuperheroMan824665 天前
部署时报错:Type 'string' is not assignable to type 'never'(Prisma 关联字段问题)
nestjs
郭俊强7 天前
nestjs 缓存配置及防抖拦截器
缓存·nestjs·防抖
用户8001536355010 天前
在 Nest.js 中实现文件上传
nestjs
三十_11 天前
NestJS 开发必备:HTTP 接口传参的 5 种方式总结与实战
前端·后端·nestjs
关山月14 天前
使用Nest.js设计RBAC权限系统:分步指南
nestjs
百罹鸟15 天前
nestjs 从零开始 一步一步实践
前端·node.js·nestjs