【问题标题】:Inversify - Http Context is always an empty objectInversify - Http 上下文始终是一个空对象
【发布时间】:2022-12-23 14:22:39
【问题描述】:

我希望你能帮助我,我正在尝试使用 inversify 和 inversify-express-utils 构建 API。所以,我已经创建了我的控制器,API 工作正常,到目前为止没有问题,但是当我尝试访问从 BaseHttpController 继承到我的控制器的 httpContext 属性时,我看不到用户详细信息,因为这个property (httpContext) 是一个空对象,我已经像官方docs 解释的那样配置了我的自定义身份验证提供程序。

这是我的代码...

app.ts

import AuthInversifyProvider from './providers/auth-inversify.provider';

export default class Application {
  private readonly server: InversifyExpressServer;
  private readonly environment: Environment;
  private readonly rootPath = '/api/v1';

  constructor(container: Container, environment: Environment) {
    this.server = new InversifyExpressServer(container, null, {
      rootPath: this.rootPath,
    }, null, AuthInversifyProvider);
    this.environment = environment;
  }

  public initialize(): ExpressApp {
    this.server.setConfig((app) => {
      // settings
      app.set('port', this.environment.PORT);
      app.set('pkg', pkg);

      // middlewares
      app.use(morgan('dev'));
      app.use(cors());
      app.use(urlencoded({ extended: false }));
      app.use(json());

      // swagger docs...
      app.use(
        `${this.rootPath}/docs`,
        SwaggerUI.serve,
        SwaggerUI.setup(SwaggerDocsSetup)
      );
    });

    this.server.setErrorConfig((app) => {
      // Global error handling
      app.use(ErrorMiddlewareHandler);
    });

    return this.server.build();
  }
}

auth-inversify.provider.ts

/* eslint-disable max-classes-per-file */
import Interfaces from '@Interfaces/interfaces.mapping';
import IAuthService from '@Interfaces/services/iauth.service';
import IUsersService from '@Interfaces/services/iusers.service';
import { Request } from 'express';
import { inject, injectable } from 'inversify';
import { interfaces } from 'inversify-express-utils';
import { UserResponseDto } from '@Shared/dtos/users.dto';

class Principal implements interfaces.Principal {
  public details: UserResponseDto | null;
  public constructor(details: UserResponseDto | null) {
    this.details = details;
  }
  public isAuthenticated(): Promise<boolean> {
    return Promise.resolve(true);
  }
  public isResourceOwner(resourceId: unknown): Promise<boolean> {
    return Promise.resolve(resourceId === 1111);
  }
  public isInRole(role: string): Promise<boolean> {
    return Promise.resolve(role === 'admin');
  }
}

@injectable()
export default class AuthInversifyProvider implements interfaces.AuthProvider {
  @inject(Interfaces.AuthService)
  private readonly authService!: IAuthService;
  @inject(Interfaces.UsersService)
  private readonly usersSevice!: IUsersService;

  public async getUser(req: Request): Promise<interfaces.Principal> {
    try {
      const rawToken = req.headers.authorization;
      const token = rawToken?.split(' ').pop() ?? '';
      const payload = await this.authService.verifyToken(token);
      const user = this.usersSevice.getById(payload?.id ?? '');

      return new Principal(user);
    } catch (error) {
      return new Principal(null);
    }
  }
}

这是一张参考图,显示当前用户查找成功

我的控制器。

【问题讨论】:

  • 我没有完整的答案,只是怀疑。 Here 是为了注册目的创建虚假空上下文的地方,later 将其替换为真实上下文,然后 injected 进入控制器。会不会是controller用错了container?例如。 inversify 的两个实例,可能是不同的版本?

标签: typescript express inversifyjs inversify-express-utils


【解决方案1】:

您是否正在使用 Singleton 选项实例化您的新容器?如果是,请尝试使用默认选项,即 transient 而不是 Singleton。我遇到了同样的问题,它有一个空的 httpContext。

【讨论】:

    猜你喜欢
    • 2017-03-29
    • 2015-06-04
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2014-05-09
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多