1

我一直在使用 Loopback 4。我最近遇到了一个错误。身份验证成功后,我尝试从我的端点访问当前用户。我收到这个错误

13:31:07 0|index  | Unhandled error in POST /posts: 500 Error: The key 'authentication.currentUser' is not bound to any value in context application
13:31:07 0|index  |     at HomeApplication.getBinding (/Development/home/node_modules/@loopback/context/dist/context.js:596:15)
13:31:07 0|index  |     at RestServer.getBinding (/Development/home/node_modules/@loopback/context/dist/context.js:592:33)
13:31:07 0|index  |     at RequestContext.getBinding (/Development/home/node_modules/@loopback/context/dist/context.js:592:33)
13:31:07 0|index  |     at RequestContext.getValueOrPromise (/Development/home/node_modules/@loopback/context/dist/context.js:651:30)
13:31:07 0|index  |     at RequestContext.get (/Development/home/node_modules/@loopback/context/dist/context.js:574:21)
13:31:07 0|index  |     at PostController.getter [as getCurrentUser] (/Development/home/node_modules/@loopback/context/dist/inject.js:258:20)
13:31:07 0|index  |     at PostController.<anonymous> (/Development/home/dist/controllers/user/post.controller.js:57:35)

我已经在 GitHub 和 StackOverflow 上尝试了所有可用的解决方案。这几天一直在寻找解决方案。

我还尝试通过将控制台日志放入生成的文件中来自己调试它。这就是我在auth-action.provider.js中所做的

async action(request) {
    const strategy = await this.getStrategy();
    if (!strategy) {
        // The invoked operation does not require authentication.
        return undefined;
    }
    console.log(`Strategy obtained successfully`)
    const userProfile = await strategy.authenticate(request);
    if (!userProfile) {
        // important to throw a non-protocol-specific error here
        const error = new Error(`User profile not returned from strategy's authenticate function`);
        Object.assign(error, {
            code: types_1.USER_PROFILE_NOT_FOUND,
        });
        throw error;
    }
    console.log(`User obtained successfully`)
    console.log(JSON.stringify(userProfile))
    this.setCurrentUser(userProfile);
    console.log(`Called setCurrentUser`)
    return userProfile;
}

之后的结果

13:46:55 0|index  | Authenticating
13:46:55 0|index  | Strategy obtained successfully
13:46:55 0|index  | ~~ Authenticating: token --> 9823eb1940eae6df49c54698d8a71b319f0b00635321a02632965a7667d69ce68883b61d803f0691c2b393bc9841606b153fa28fc853ecfd41bd647725479b54,  mode --> personal~~
13:46:55 0|index  | User found. Id --> 5d8f549de7179a022443e34e
13:46:55 0|index  | User obtained successfully
13:46:55 0|index  | {"email":"my@email.com","id":"5d8f549de7179a022443e34e","name":"name","image":null,"designation":"Designation","company":"string"}
13:46:55 0|index  | Called setCurrentUser
13:46:55 0|index  | Trace: Error: The key 'authentication.currentUser' is not bound to any value in context application
13:46:55 0|index  |     at HomeApplication.getBinding (/Development/home/node_modules/@loopback/context/dist/context.js:596:15)
13:46:55 0|index  |     at RestServer.getBinding (/Development/home/node_modules/@loopback/context/dist/context.js:592:33)
13:46:55 0|index  |     at RequestContext.getBinding (/Development/home/node_modules/@loopback/context/dist/context.js:592:33)
13:46:55 0|index  |     at RequestContext.getValueOrPromise (/Development/home/node_modules/@loopback/context/dist/context.js:651:30)
13:46:55 0|index  |     at RequestContext.get (/Development/home/node_modules/@loopback/context/dist/context.js:574:21)
13:46:55 0|index  |     at PostController.getter [as getCurrentUser] (/Development/home/node_modules/@loopback/context/dist/inject.js:258:20)
13:46:55 0|index  |     at PostController.<anonymous> (/Development/home/dist/controllers/user/post.controller.js:57:35)

如您所见,一切都按预期工作。只是当我尝试在我的控制器中获取用户时,会发生此错误。如果我不尝试访问用户,一切正常。

我的猜测是在auth-action.provider中注入的setCurrentUser方法有问题。

如果您需要,这是我的控制器。

export class PostController {

  static MAX_POST_LENGTH = 800;

  constructor(
    @repository(PostRepository)
    public postRepository: PostRepository,
    @inject(MyAuthBindings.USER_TOKEN_SERVICE)
    public userTokenService: UserTokenService,
    @inject.getter(AuthenticationBindings.CURRENT_USER)
    public getCurrentUser: Getter<MyUserProfile>,
  ) {
  }

  @post('/posts', {
    responses: {
      '200': {
        description: 'Post model instance',
        content: {'application/json': {schema: {'x-ts-type': UserPost}}},
      },
    },
  })
  @authenticate('user')
  async create(
    @param.header.string('token') token: string,
    @param.header.string('mode') mode: string,
    @requestBody() newPostRequest: PostRequest): Promise<UserPost> {

    if (newPostRequest.body.length > PostController.MAX_POST_LENGTH) {
      throw new HttpErrors.BadRequest(`Post body cannot be larger than ${PostController.MAX_POST_LENGTH} characters`);
    }

    let user = await this.getCurrentUser();

    console.log(`Authenticated user --> ${JSON.stringify(user, null, 2)}`);

    let postItem = new Post(newPostRequest);
    postItem.userId = user.id;
    postItem.createdAt = new Date();
    postItem.updatedAt = new Date();
    postItem = await this.postRepository.create(postItem);

    if (postItem.id != null)
      PostController.checkAndSendStyleworkPostNotification(user.id, postItem.id);

    return new UserPost(postItem, user, user);
  }

处理没有到达上述方法中的日志。

PS 这个问题在@loopback/authentication 从 2.2.2 更新到 3.0.0 之后开始出现

4

1 回答 1

0

我解决了这个问题。正如 Authentication 组件文档中指出的那样,该问题AuthenticationBindings.CURRENT_USER现在是 @loopback/security中SecurityBindings.USER的别名。

我只需要用 SecurityBindings.USER 替换 AuthenticationBindings.CURRENT_USER。正如我在问题中指出的那样,此更改是在 v3.0.0 中进行的。

于 2019-11-13T09:26:02.367 回答