生成guard.ts
nest g gu role
// role.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class RoleGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
console.log('经过了守卫');
return true;
}
}
配置controller
// guard.controller.ts
import { Controller, UseGuards, Get } from '@nestjs/common'
import { RoleGuard } from './role.guard'
@Controller()
@UseGuards(RoleGuard)
export class GuardController {
@Get()
guardTest() {
return 'guard test'
}
}
// controller
import { Controller, UseGuards, Get, SetMetadata } from '@nestjs/common'
import { RoleGuard } from './role.guard'
@Controller()
@UseGuards(RoleGuard)
export class GuardController {
@Get()
@SetMetadata('role', ['admin']) // 两个参数可自定义,(key, value), 可以用key, value 做后期的判断逻辑
metaGuardTest() {
return 'meta guard test'
}
}
// guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core'
import type { 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'/* 此key 值为SetMetadata中定义的key值 */, contest.getHandler())
const req = context.switchToHttp().getRequest<Request>()
console.log('经过了守卫', admin, req);
// 做权限验证,如果有就过
if (admin.includes(req.query.role as string)) {
return true
} else {
return false
}
}
}
import { RoleGuard } from './role.guard'
app.useGlobalGuards(new RoleGuard())