Nestjs:每个请求的AuthGuard验证?

时间:2020-02-10 10:39:09

标签: authentication nestjs

我有一个nestjs graphql后端,我想每个http请求一次进行令牌认证。

问题:

对于一个http请求,如果我有以下graphql查询,则我的全局定义防护app.useGlobalGuards(new GqlAuthGuard())将验证用户 7次

  {
    article(id:1)
    {
      id
      name   
    }
    categories {
      id
      name
    }
    topics {
      id
      name              
    }
    lawmakers {
      id
      name
    }
    articleTypes {
      id
      name
    }
    articleStatuses {
      id
      name
    }
    countries {
      id
      name
    }
  }

似乎每个受查询影响的模块都调用AuthGuard。

如何摆脱这种多重验证?

1 个答案:

答案 0 :(得分:0)

您可能最终可能会在请求上下文中附加某种validatedauthenticated属性,以便在每个新的保护措施下,通过该字段的请求都会被缩短。问题在于,对于您的查询,您本质上一次进行了7次http调用,并且Nest将针对每个请求的查询和变异运行防护措施,因为这是绑定全局防护措施的方式。解决此问题的唯一实际方法是添加某种短路,以使复杂的逻辑不会发生。