【问题标题】:Can't retrieve user un AuthGuard but in Decorator in NestJS无法检索用户 un AuthGuard 但在 NestJS 的装饰器中
【发布时间】:2022-01-27 03:10:45
【问题描述】:

我在 NestJS 中实现了一个 Graphql API,并带有一个保护机制,以防止某些角色访问给定的路由。到目前为止,我能够通过GQLExecutionContextCurrentUser 装饰器中检索用户。但不是在警卫队。

下面是警卫:

  import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
  import { Reflector } from '@nestjs/core';
  import { Observable } from 'rxjs';
  import { GqlExecutionContext } from '@nestjs/graphql';

  @Injectable()
  export class AdminGuard implements CanActivate {
    constructor(private reflector: Reflector) {}

    canActivate(
      context: ExecutionContext,
    ): boolean | Promise<boolean> | Observable<boolean> {
      const roles = this.reflector.get<string[]>('roles', context.getHandler());
      if (!roles) {
        return true;
      }
      const ctx = GqlExecutionContext.create(context);
      console.log('adminguard', ctx.getContext().req.user);
      const request = ctx.getContext().req;
      const user = request.user;
      return roles.includes(user?.role);
    }
  }

这里是装饰器:

  import { createParamDecorator, ExecutionContext } from '@nestjs/common';
  import { GqlExecutionContext } from '@nestjs/graphql';

  export const CurrentUser = createParamDecorator(
   (data: unknown, context: ExecutionContext) => {
      const ctx = GqlExecutionContext.create(context);
      console.log('current user', ctx.getContext().req.user);
      return ctx.getContext().req.user;
    },
  );

大家一起:

@Resolver(() => User)
export class UsersResolver {
  constructor(private readonly usersService: UsersService) {}

  @Roles('admin')
  @UseGuards(GqlAuthGuard)
  @Query(() => [User], { name: 'users' })
  findAll(@CurrentUser() user: User) {
    return this.usersService.findAll();
  }
}

我的应用模块像这样实现Graphql

   GraphQLModule.forRoot({
     autoSchemaFile: './schema.gql',
     context: ({ req }) => ({ req }),
     debug: true,
     playground: true,
   }),

我希望能够像使用装饰器一样在 AdminGuard 中检索用户。感谢您的帮助。

【问题讨论】:

    标签: typescript routes graphql nestjs guard


    【解决方案1】:

    我的错误是认为@Roles('admin') 在后台调用了我的AdminGuard。 为了修复代码,我将AdminGuard 重命名为RolesGuard。然后我像这样修复了实现:

      @Roles(['admin']) // 1. first define authorized role
      @UseGuards(RolesGuard) // 2. then bind RolesGuard
      @UseGuards(GqlAuthGuard) // 3. finally use the GqlAuthGuard
      @Query(() => [User], { name: 'users' })
      findAll(@CurrentUser() user: User) {
        return this.usersService.findAll();
      }
    

    【讨论】:

      猜你喜欢
      • 2019-09-10
      • 2021-10-17
      • 2021-12-27
      • 1970-01-01
      • 2018-12-27
      • 2023-01-04
      • 1970-01-01
      • 2021-11-25
      • 2021-05-17
      相关资源
      最近更新 更多