守卫
原创...大约 2 分钟
守卫是一个用 @Injectable()
装饰器注释的类,它实现了 CanActivate
接口。
守卫有一个 单一职责。 它们根据运行时存在的某些条件(如权限、角色、ACL 等)确定给定请求是否将由路由处理程序处理。 这通常称为 authorization
。 在传统的 Express
应用中,授权(及其表亲 authentication,通常与之合作)通常由 middleware 处理。 中间件是身份验证的不错选择,因为诸如令牌验证和将属性附加到 request 对象之类的事情与特定路由上下文(及其元数据)没有紧密联系。
但是中间件,就其本质而言,是愚蠢的。 它不知道调用 next()
函数后将执行哪个处理程序。 另一方面,守卫 可以访问 ExecutionContext
实例,因此确切地知道接下来要执行什么。 它们的设计与异常过滤器、管道和拦截器非常相似,可让你在请求/响应周
现在我们生成一个守卫
nest g gu ./guard/authentication
在src/guard
目录下,我们生成了一个身份认证的守卫
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthenticationGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
return true;
}
}
简单修改
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthenticationGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const token = "前端请求携带"
if (token) {
console.log("身份认证成功");
return true;
} else {
console.log("身份认证失败");
return false;
}
}
}
使用
import { Controller, Get, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { AuthenticationGuard } from 'src/guard/authentication/authentication.guard';
@UseGuards(AuthenticationGuard)
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) { }
@Get("")
findAll() {
return "1"
}
}
也可以直接在路由上使用
import { Controller, Get, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { AuthenticationGuard } from 'src/guard/authentication/authentication.guard';
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) { }
@UseGuards(AuthenticationGuard)
@Get("")
findAll() {
return "1"
}
}
此时,我们访问http://localhost:3000/user
进行查看,在控制台看到了身份认证成功
,很明显守卫已经被触发了
Powered by Waline v2.15.7