nest守卫主要有三种方式
先执行命令:nest g res guard,创建一个名为guard的res资源文件并进入,nest g gu role,在guard资源文件里面创建一个名为role的守卫文件
方式一:全局使用守卫
在main.ts 文件中
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import * as cors from 'cors'
import { VersioningType, ValidationPipe } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express'
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
// 全局的守卫
import { RoleGuard } from './guard/role/role.guard'
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// 使用全局守卫
app.useGlobalGuards(new RoleGuard())
await app.listen(3000);
}
bootstrap();
方式二:单个server使用
在guard.controller.ts中
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, SetMetadata } from '@nestjs/common';
import { GuardService } from './guard.service';
import { CreateGuardDto } from './dto/create-guard.dto';
import { UpdateGuardDto } from './dto/update-guard.dto';
//引入守卫文件
import {RoleGuard} from './role/role.guard'
@Controller('guard')
//使用UseGuards装饰器使用守卫
@UseGuards(RoleGuard)
export class GuardController {
constructor(private readonly guardService: GuardService) {}
@Get()
findAll() {
return this.guardService.findAll();
}
}
方式三:智能使用守卫
还是在guard.controller.ts中
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, SetMetadata } from '@nestjs/common';
import { GuardService } from './guard.service';
import { CreateGuardDto } from './dto/create-guard.dto';
import { UpdateGuardDto } from './dto/update-guard.dto';
//引入守卫文件
import {RoleGuard} from './role/role.guard'
@Controller('guard')
//使用UseGuards装饰器使用守卫
@UseGuards(RoleGuard)
export class GuardController {
constructor(private readonly guardService: GuardService) {}
@Get()
//使用SetMetadata为此方法添加元信息,在守卫中可以获取此信息进行业务判断
@SetMetadata('role',['admin'])
findAll() {
return this.guardService.findAll();
}
}
在role/role.guard.ts中
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
//获取路由的元信息需要用到nest核心库中的反射Reflector
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private Reflector: Reflector) { }
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const admin = this.Reflector.get<string[]>('role', context.getHandler())
const req:Request = context.switchToHttp().getRequest()
// if()
console.log('守卫', req.query.role);
console.log('守卫', admin);
if(admin.includes(req.query.role as string)){
return true
}else{
return false
}
}
}