环回 4:如何在端点中注入用户

apf*_*pfz 7 loopback4

我有一个端点,用户和来宾(未经过身份验证)都可以将数据发布到:

 async create(
    @requestBody({
      content: {
        'application/json': {
          schema: {
            type: 'object',
            properties: {
              create_account: {type: 'boolean'},
              password: {type: 'string'},
              password_repeat: {type: 'string'},
              currency: {type: 'string'},
              payment_method: {type: 'string'},
              products: {type: 'array'},
              voucher: {type: 'string'},
              customer: {type: 'object'},
              news_letter: {type: 'boolean'},
            },
          },
        },
      },
    })
    @inject(SecurityBindings.USER) currentUserProfile: UserProfile,
    order: Omit<Order, 'id'>,
  ): Promise<{url: string}> {
       const userId = currentUserProfile[securityId];
  }
Run Code Online (Sandbox Code Playgroud)

但是,我不确定如何从会话中获取登录用户,因为我收到以下错误:

The key 'security.user' is not bound to any value in context
Run Code Online (Sandbox Code Playgroud)

在这种情况下如何获取用户 ID?

小智 3

@authenticate()控制器端点需要使用和装饰器进行装饰@authorize(),并且必须事先设置身份验证系统。

身份验证和授权文档最近已进行了彻底修改。请参阅它们作为权威指南。

例如,

  @post('/users/{userId}/orders', {
    responses: {
      '200': {
        description: 'User.Order model instance',
        content: {'application/json': {schema: {'x-ts-type': Order}}},
      },
    },
  })
  @authenticate('jwt')
  @authorize({resource: 'order', scopes: ['create']})
  async createOrder(
    @param.path.string('userId') userId: string,
    @requestBody() order: Order,
  ): Promise<Order> {
    await this.userRepo.orders(userId).create(order);
  }
Run Code Online (Sandbox Code Playgroud)

不幸的是,如果没有更多信息(例如身份验证策略和授权提供者),就不可能给出明确的解决方案,因为不同的 UAA 实现将有不同的解决方案。

进一步阅读