nestjs - NestJS - 组合多个警卫并在一个返回 true 时激活
问题描述
我有一个问题。
是否可以在一条路线上使用多个身份验证守卫(在我的情况下是基本身份验证和 ldap 身份验证)。当一个守卫成功时,应该对路由进行身份验证。
解决方案
简短回答:不,如果您在一条路线上添加多个守卫,他们都需要通过才能激活路线。
长答案:但是,通过使您的 LDAP 保护扩展基本保护,您可以尝试完成。如果 LDAP 特定逻辑成功,则返回true
,否则返回调用结果到super.canActivate()
。然后,在您的控制器中,将基本或 LDAP 保护添加到您的路由中,但不能同时添加两者。
基本的.guard.ts
export BasicGuard implements CanActivate {
constructor(
protected readonly reflector: Reflector
) {}
async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
if () {
// Do some logic and return true if access is granted
return true;
}
return false;
}
}
ldap.guard.ts
export LdapGuard extends BasicGuard implements CanActivate {
constructor(
protected readonly reflector: Reflector
) {
super(reflector);
}
async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
if () {
// Do some logic and return true if access is granted
return true;
}
// Basically if this guard is false then try the super.canActivate. If its true then it would have returned already
return await super.canActivate(context);
}
}
有关更多信息,请参阅官方 NestJS 存储库上的这个 GitHub 问题。
推荐阅读
- javascript - 函数返回null,等待结果未应用
- javascript - Reactjs 中的网络状态检测
- ssh - Google-Compute-Engine 虚拟机实例:添加磁盘后无法登录/SSH 虚拟机实例
- face-recognition - Private Identity 生成的加密 FHE 有效载荷与基于云的生物识别系统生成的模板有何不同?
- react-native - React Native FAILURE:构建失败并出现异常
- react-native - RNCNetinfo.getCurrentState 有 3 个参数,预期为 2
- git - 基于主干开发的代码审查
- flutter - 如何在颤动的弹出菜单中实现下拉菜单
- javascript - 单击时如何向按钮添加超链接,打开一个显示函数结果的新窗口(不是选项卡)?
- python-3.x - 使用 Newspaper3k 时从 html 中删除嵌入的推文