0
votes

I'm trying to access the user token of my silex app outside of a request in order to manage includes depending on the logged in user. Since it's not working I broke down my script to be like this:

// .. I have registered the app and some other providers before this ...

// Register the firewall
$app->register(new Silex\Provider\SecurityServiceProvider());
$app->register(new Silex\Provider\RememberMeServiceProvider());

$app['security.firewalls'] = array(
    'login' => array(
        'pattern' => '^/login$',
    ),
    'secured' => array(
        'pattern' => '^.*$',
        'security' => true,
        'form' => array(
            'login_path' => '/login',
            'check_path' => '/login_check'
        ),
        'logout' => array(
            'logout_path' => '/logout',
            'invalidate_session' => true
        ),
        'users' => array(
            // raw password is foo
            'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
        )
    )
);

// Boot the application to access security features
$app->boot();

// Get the token
$token = $app['security']->getToken();
var_dump($token);

// ... Here comes the route definition ...

$app->run();

The application is running and when I'm not logged in the token is NULL, what is right. But if I'm logged in the token is also NULL as long I access it outside the request. If I access it inside the request it is set. Silex documentation says:

The security features are only available after the Application has been booted. So, if you want to use it outside of the handling of a request, don't forget to call boot() first:

$app->boot();

I thought this way I can access the token outside the request, but it's not working. Am I doing something wrong or didn't I get the documentation right?

1

1 Answers

0
votes

Security token is set in $app->run(); on KernelEvents::REQUEST event.

If you want to make something before base code add KernelEvents::REQUEST event listener or middleware.

$app->before(function($event, $app) {
    $request = $event->getRequest();
    $token = $app['security']->getToken();

    // your code here
})

http://silex.sensiolabs.org/doc/middlewares.html