Silex:令牌存储不包含身份验证令牌

Silex : The token storage contains no authentication token

在布局中尝试检查用户是否经过身份验证时

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

我收到一个错误,因为

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.

这是安全防火墙的配置。我只需要允许登录用户访问该网站。

$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
    )
));

欢迎提出解决此问题的任何想法。

谢谢

由于错误消息说错误发生在 layout.html,我猜它被用在每个页面上,即使是像 /login 这样不在防火墙后面的页面。该错误是由于未在防火墙后调用 is_granted 引起的。

所以有几个选项:

  1. 为不调用 is_granted
  2. 的登录页面使用单独的布局
  3. 调用前检查是否存在安全令牌is_granted

选项 1 应该是显而易见的,因此不再赘述。

使用选项 2,您可以像这样检查现有的安全令牌:

{% if app.security.token is not null and is_granted('IS_AUTHENTICATED_FULLY') %}