我可以否决NestJS的守卫吗?

时间:2020-02-18 22:23:13

标签: typescript passport.js nestjs nestjs-passport

我在一种方法(路线)上使用了AuthGuard中的@nestjs/passport,如下所示:

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

我可以否定此防护措施,因此只有没有JWT的用户才能进入低谷?我不希望标题中包含JWT的用户意外访问登录/注册路由。

1 个答案:

答案 0 :(得分:1)

正如bashleigh在她的评论中所说,您可以创建自己的警卫来检查jwt并拒绝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)