我已经开始学习Nestjs、express和graphql。我在尝试授权使用 jwt 令牌进行身份验证的用户访问时遇到问题。我按照Nestjs 网站上的身份验证教程进行操作。我能够获取当前用户,但是当我尝试实现基本角色基础访问控制时,我无法在 canActivate 方法中访问当前用户。我认为这是因为 Roles Guard 在 Graphql Guard 之前执行。
我将在这里发布代码
gql-auth.guard.ts
import { ExecutionContext } from "@nestjs/common";
import { GqlExecutionContext } from "@nestjs/graphql";
import { AuthGuard } from "@nestjs/passport";
export class GqlAuthGuard extends AuthGuard("jwt") {
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
console.log("gql simple context: ", context);
console.log("gqlContext: ", ctx.getContext());
return ctx.getContext().req;
}
}
Run Code Online (Sandbox Code Playgroud)
角色.guard.ts
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { GqlExecutionContext } …Run Code Online (Sandbox Code Playgroud)