您的位置:首页 > 游戏 > 游戏 > NestJS中使用Guard实现路由保护

NestJS中使用Guard实现路由保护

2024/10/6 6:45:42 来源:https://blog.csdn.net/kongxx/article/details/142074362  浏览:    关键词:NestJS中使用Guard实现路由保护

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

什么是Guard?

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

如何创建Guard?

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

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装饰器。

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。

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中的路由处理器。

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

{"message":"Forbidden resource","error":"Forbidden","statusCode":403
}

总结

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com