silexphp / Silex

[DEPRECATED -- Use Symfony instead] The PHP micro-framework based on the Symfony Components
https://silex.symfony.com
MIT License
3.58k stars 718 forks source link

Initialize security context on kernel.exception #566

Closed nlegoff closed 11 years ago

nlegoff commented 11 years ago

This week I ran into an issue where, I needed to display user informations when an authenticated user hits /page-not-found.

404

The problem was that the token I get from the security service in the silex error handler callback was always null despite my /page-not-found being behind a security firewall rule.

To resume

<?php
$app->error(function(\Exception $e, $code) use ($app) {
    $app['security']->getToken() // is always null
});

After digging the code I found out that the security context was initialized when the kernel.request event is triggered see https://github.com/fabpot/Silex/blob/master/src/Silex/Provider/SecurityServiceProvider.php#L509

But when someone hits /page-not-found the 'kernel.exception' is triggered not ''kernel.request thus security context is never initialized.

As a workaround I have quickly added the onKernelRequest method from the Firewall object that initialize the context to be triggered on kernel.exception event ...

<?php
$app = new Silex\Application();

$app['dispatcher']->addListener('kernel.exception', array($app['security.firewall'], 'onKernelRequest'), 8);

$app->run();

What do you guys think about this behavior of not being able to retrieve user credentials in error handler ? Does the security context should be initialized on kernel.exception ? If yes should it be by default on silex security provider ? Or on user demand only ?

davedevelopment commented 11 years ago

I think the kernel.request event is fired, but the RouterListener listens at a greater priority and throws before the firewall listener ever gets chance to do it's thing.

nlegoff commented 11 years ago

Indeed, you are right RouterListener listens at a priority of 32 and Firewall listener at a priority of 8.