【问题标题】:LexikJWTAuthenticationBundle: Get current user on server sideLexikJWTAuthenticationBundle:获取服务器端的当前用户
【发布时间】:2018-06-16 09:52:59
【问题描述】:

我正在使用 Symfony 3.4 和 LexikJWTAuthenticationBundle 2.4。您知道如何检索正在访问 API 端点的用户吗?

通常,我会打电话给$user = $this->get('security.token_storage')->getToken()->getUser();,但在这种情况下似乎不起作用。

【问题讨论】:

  • 您应该能够在控制器public function someAction(UserInterface $user) 中输入提示当前用户,如果它不起作用,您会收到任何错误吗?如果没有任何帮助,我会尝试再次检查 LexikJWT 的配置步骤

标签: symfony jwt lexikjwtauthbundle


【解决方案1】:

给你的建议,在控制器中使用 container 键。

当然,最好在这里发送您的错误!

Symfony 4

protected function getCurrentUser()
    {

        if (!$this->container->has('security.token_storage')) {
            throw new \LogicException('The Security Bundle is not registered in your application.');
        }
        if (null === $token = $this->container->get('security.token_storage')->getToken()) {
            return;
        }
        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return;
        }
        return $user;
    }

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,您可以使用以下方法获取当前用户的 ID:

    $current_user = $this->getUser();
    
    $id = $current_user->getId();
    

    在您的控制器内部。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-12
      • 2015-09-12
      • 1970-01-01
      • 2020-11-23
      • 2016-12-26
      • 1970-01-01
      • 2016-12-09
      • 2023-03-12
      相关资源
      最近更新 更多