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。

相关推荐
白雾茫茫丶10 天前
Nest.js 实战 (十二):优雅地使用事件发布/订阅模块 Event Emitter
nestjs·nest.js·发布订阅·event emitter
lph65821 个月前
比起上传资源更应该懂得如何资源回收
node.js·nestjs
gsls2008081 个月前
将nestjs项目迁移到阿里云函数
阿里云·云计算·nestjs·云函数
d3126975101 个月前
在Nestjs使用mysql和typeorm
mysql·express·nestjs·typeorm
剪刀石头布啊2 个月前
nestjs-版本控制
nestjs
潇洒哥gg2 个月前
重生之我在NestJS中使用jwt鉴权
前端·javascript·nestjs
huangkaihao2 个月前
【NestJS学习笔记】 之 自定义装饰器
前端·node.js·nestjs
鹿鹿鹿鹿isNotDefined2 个月前
Nest 源码解析:依赖注入是怎么实现的?
nestjs
剪刀石头布啊2 个月前
nestjs-自定义装饰器
nestjs