【问题标题】:User is undefined on the context.switchToHttp().getRequest() nestjs用户在 context.switchToHttp().getRequest() nestjs 上未定义
【发布时间】:2021-07-30 21:14:15
【问题描述】:

我是nestJs 的新手,我需要为应用程序添加基于角色的访问权限,因此我遵循了文档,但在执行上下文中用户不存在。如果您需要查看更多代码,我似乎无法在 github 存储库中找到问题:https://github.com/anjula-sack/slinc-backend

roles.guard.ts

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from 'src/decorators/roles.decorator';
import Role from 'src/util/enums/role.enum';

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

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!requiredRoles) {
      return true;
    }
    const { user } = context.switchToHttp().getRequest();
    console.log(context.switchToHttp().getRequest().req);

    return requiredRoles.some((role) => user.type === role);
  }
}

app.controller.ts

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Get('me/business')
  @Roles(Role.ADMIN)
  getBusiness(@Request() req) {
    return this.usersService.getUserBusiness(req.user.id);
  }

【问题讨论】:

  • 你有没有偶然将RolesGuard 绑定到全球?
  • 是的,它在 app.module.ts 中
  • 您能分享您遵循的文档吗?另外,您能解释一下您是如何在请求中发送user 的吗?它是在标题还是正文中?我试过你发布的github URL,但我猜它是一个私人存储库所以我看不到
  • 现在可以查看了吗?我公开了@ErangaHeshan

标签: javascript node.js jwt nestjs roles


【解决方案1】:

从代码来看,我认为你是在混合全局和本地警卫

app.module.ts,下面的代码是注册全局守卫的。 和app.useGlobalGuard() 应该一起使用,如果你想全局应用防护。

// Remove the following code in app.module.ts
{
    provide: APP_GUARD,
    useClass: RolesGuard,
}

但是您的意图应该是构建一个本地角色保护,所以请删除上面的代码,请求用户将工作。

【讨论】:

  • 如果我想将角色守卫用作全局怎么办?我不想在每个控制器中都提到它。
猜你喜欢
  • 2020-02-18
  • 2021-10-17
  • 2021-07-10
  • 2020-08-25
  • 2021-09-30
  • 2022-01-17
  • 2021-11-23
  • 2019-08-01
  • 2021-03-09
相关资源
最近更新 更多