相关疑难解决方法(0)

NestJS在通过JWT认证的GraphQL解析器中获取当前用户

我目前正在将Passport.js的JWT身份验证实现到NestJS应用程序中。

在某些GraphQL解析器中,我需要访问当前经过身份验证的用户。我知道通行证会将经过身份验证的用户附加到请求对象(至少我希望这是正确的),但是我不知道如何访问解析器中的请求对象。

我关注了这个问题https://github.com/nestjs/nest/issues/1326和提到的链接https://github.com/ForetagInc/fullstack-boilerplate/tree/master/apps/api/src/app/auth里面的问题。我看到一些代码,使用@Res() res: Request作为GraphQL解析方法的方法参数,但我总是undefinedres

这些是我目前拥有的实现:

GQL验证

import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { GqlExecutionContext } from '@nestjs/graphql';
import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';
import { AuthenticationError } from 'apollo-server-core';

@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
  canActivate(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    const { req } = ctx.getContext();
    console.log(req);

    return super.canActivate(new ExecutionContextHost([req]));
  }

  handleRequest(err: any, user: any) {
    if (err …
Run Code Online (Sandbox Code Playgroud)

node.js jwt graphql nestjs

7
推荐指数
2
解决办法
2212
查看次数

标签 统计

graphql ×1

jwt ×1

nestjs ×1

node.js ×1