flint
flint

Reputation: 345

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()

Upvotes: 1

Views: 366

Answers (1)

maddob
maddob

Reputation: 1009

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:

  • security
  • security.authentication_manager
  • security.access_manager
  • security.session_strategy
  • security.user_checker
  • security.last_error
  • security.encoder_factory
  • security.encoder.digest

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!!!

Upvotes: 1

Related Questions