【问题标题】:Symfony Service Configurator: getToken with security.context is NULLSymfony 服务配置器:getToken with security.context 为 NULL
【发布时间】:2014-10-20 22:15:31
【问题描述】:

我在我的项目中使用 Symfony Service Configurator 在实例化后配置服务 (Docs), 在配置方法中,我需要登录当前用户,因此我注入容器并尝试从 Security.context 服务中获取令牌,但始终为 NULL。 我还尝试在我的 Configurator 构造中只注入 Security.context 但我得到了相同的结果。

大家有什么想法

谢谢。

类 MyConfigurator { 私人$容器; 公共函数 __construct(ContainerInterface $container) { $this->container = $container; } 公共功能配置() { $user = $this->container->get('security.context')->getToken(); var_dump($user); // = 空 } }

【问题讨论】:

  • 你登录了吗??
  • @skowron-line 是的,我已登录
  • 检查 stackoverflow.com/questions/11167979/… 看看是否有帮助
  • @joaoalves 感谢您的回复,但我没有使用侦听器以高优先级发送它。
  • 我想你的服务是在 security.context 填充之前创建的。

标签: symfony security-context


【解决方案1】:

更好的方法应该是:

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class MyConfigurator
{
     private $tokenStorage;

     public function __construct(EntityManager $em, TokenStorage $tokenStorage)
     {
         $this->em = $em;
         $this->tokenStorage= $tokenStorage;
     }

     public function configure()
     {
         $user = $this->tokenStorage->getToken()->getUser();
     }

     ....

【讨论】:

    【解决方案2】:

    我通过从会话中获取 UserId 并从数据库中获取当前用户来解决问题。

    UserId 之前由我的项目中的 AuthenticationListener 设置。 所以我将我的 Configurator 构造修改为:

    /** * @param EntityManager $em * @param 会话 $session */ 公共函数 __construct(EntityManager $em, 会话 $session) { $this->em = $em; $this->session = $session; }

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 2017-03-27
      • 2019-11-18
      • 1970-01-01
      相关资源
      最近更新 更多