securitysilex

Access Symfony/Silex user data in security


How can I access the currently logged in User's Id from the Symfony security session? I'm not in inside a class so $this->get('security.context')->getToken() doesn't work. Here is what hasn't worked so far:

$app->get('security.context')->getToken()
$app->getToken()
$app->secruity->getToken()

Solution

  • You have some errors in your spelling:

    $app->secruity->getToken() // You have written SECRUITY!!!

    $app->security->getToken() // Fixed Version

    Maybe this is the reason that it's not working. The SecurityProvider component provides the following services:

    So I guess security.context will not work in silex...

    As written in the documentation you can access the SecurityProvider instance by:

    $app['security'];
    

    To get the current user you can use:

    $token = $app['security']->getToken();
    if (null !== $token) {
        $user = $token->getUser();
    }
    

    For more information read the documentation of the SecurityServiceProvider

    Also make sure you have registered the SecurityServiceProvider within your app!!!