【问题标题】:Can I negate NestJS's Guard?我可以否定 NestJS 的 Guard 吗?
【发布时间】:2020-06-03 00:42:18
【问题描述】:

我在我的一个方法(路线)上使用了来自@nestjs/passportAuthGuard,如下所示:

  @UseGuards(AuthGuard('jwt'))
  @Get('profile')
  getProfile(@Req() req) {
    return this.userService.findOne(req.user.id);
  }

我可以否定这个守卫,所以只有没有 JWT 的用户才能通过?我不希望标头中带有 JWT 的用户意外访问登录/注册路由。

【问题讨论】:

  • 是的!建立一个新的守卫,将拒绝使用 jwt 的请求

标签: typescript passport.js nestjs nestjs-passport


【解决方案1】:

正如 bashleigh 在她的评论中所说,您可以创建自己的警卫来检查 jwt 并在它进入时拒绝。一个简单的例子可能是这样的

@Injectable()
export class NoJwtGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const req = context.switchToHttp().getRequest();
    const auth = req.headers['Authroization'];
    // as you should not have any authorization headers you an reject if the header exists
    return !auth;
  }
}

虽然不可能立即否定内置保护,但您也可以扩展 AuthGuard('jwt'),然后在您的 canActivate 的自定义实现中,您可以 return !super.canActivate(context)

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 2020-02-10
    • 2014-01-26
    • 1970-01-01
    • 2021-10-12
    • 2015-02-07
    • 1970-01-01
    • 2022-12-24
    • 2021-05-08
    相关资源
    最近更新 更多