Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silex : The token storage contains no authentication token

Tags:

silex

When trying to check whether the user is authenticated or not in layout

{% if is_granted('IS_AUTHENTICATED_FULLY') %}
    <p>Username: {{ app.user.username }}</p>
{% endif %}

I am getting an error as

Twig_Error_Runtime in Template.php line 304:
An exception has been thrown during the rendering of a template ("The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.") in "layout.html" at line 39.

This is the configuration of the security firewall. I need to only allow logged in users to access the website.

$app->register(new SecurityServiceProvider(), array(
    'security.firewalls' => array(
        'dev' => array(
            'pattern' => '^/(_(profiler|wdt)|css|images|js)/',
            'security' => false
        ),
        'login' => array(
            'pattern' => '^/login$',
        ),
        'secured' => array(
            'pattern' => '^.*$',
            'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
            'logout' => array('logout_path' => '/logout'),
            'users' => $app->share(function() use ($app) {
                // Specific class App\User\UserProvider is described below
                return new App\User\UserProvider($app['db']);
            }),
        ),
        'unsecured' => array(
            'anonymous' => true,
        )
    ),
    'security.access_rules' => array(
        // You can rename ROLE_USER as you wish
        array('^/.+$', 'ROLE_USER'),
        array('^/login$', 'SS'), // This url is available as anonymous user
    )
));

Any ideas to fix this is welcome.

Thank you

like image 665
Hari K T Avatar asked Jan 15 '15 07:01

Hari K T


1 Answers

Since the error message says that the error happens in layout.html, I'm guessing it is used on every page even the ones like /login that is not behind a firewall. The error is caused by calling is_granted when not behind a firewall.

So there are a few options:

  1. Use a separate layout for login page that does not call is_granted
  2. Check if there is an existing security token before calling is_granted

Option 1 should be obvious so not going into more detail with that.

With option 2, you can do something like this to check for existing security token:

{% if app.security.token is not null and is_granted('IS_AUTHENTICATED_FULLY') %}
like image 178
Cvuorinen Avatar answered Oct 12 '22 23:10

Cvuorinen