Symfony2休息和oauth,不能持续会话

时间:2014-07-07 09:03:02

标签: session symfony

我正在使用FosRestBundle和FosOauthServerBundle作为Symfony的api。

我有一条路线/login/username/password,在此操作中我手动登录用户:

            $encoder_service = $this->get('security.encoder_factory');
            $encoder = $encoder_service->getEncoder($user);
            $encoded_pass = $encoder->encodePassword($password, $user->getSalt());

            if ($user->getPassword() == $encoded_pass) {
                $token = new UsernamePasswordToken($user, $password, "api", $user->getRoles());
                $this->get("security.context")->setToken($token);

                $event = new InteractiveLoginEvent($this->get("request"), $token);
                $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
            }

如果我在那之后检查我的数据库(我在我的数据库中保存会话)我有一个新行,并且在我的行动结束时,如果我检查$this->getUser()我有一个好的。

但在那之后,在另一个动作中,如果我检查$ this-> getUser()我注意到...我无法将一个用户会话从一个动作检索到另一个动作。

你有什么想法吗?

Ediy:如果我检查$this->container->get('security.context')->getToken()我有:

{"roles":[{"role":"ROLE_USER"}],"authenticated":true,"attributes":[],"token":"MYTOKEN"}

但我没有我的用户..

1 个答案:

答案 0 :(得分:0)

您应该能够从安全上下文中获取用户。我通常将其定义为我需要它的控制器中的单独函数:

public function getConnectedUser()
{
    $user = null;

    if ($this->get('session')->has('_security_member') && !is_null($this->get('security.context')->getToken())) {
        $user = $this->get('security.context')->getToken()->getUser();
    }

    return $user;
}

然后,您可以从控制器的每个操作中访问它。

$user = $this->getConnectedUser();