Silex - access to user outside a secured area

2019-09-14 16:03发布

问题:

I have set up a secured area in my Silex website. I need to display the username in the header when the user is connected or a link to the login form if the user is not connected. But when the user is on a page not secured (outside the firewall), the app.user is not defined.

I have tried this solution, but it does not work.

Here my security configuration:

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
    'security.firewalls' => array(
        'account' => array(
            'pattern' => '^/account',
            'form' => array('login_path' => '/login', 'check_path' => '/account/login_check'),
            'users' => $app->share(function () use ($app) {
                return new UserProvider($app['db']);
            }),
        ),
        'unsecured' => array(
            'anonymous' => true,
        ),
    )
));

And here my header where I'm displaying the username:

{% if app.user %}
    {{ app.user.username }}<br />
        <a href="{{ path('account') }}">Mon compte</a>
    {% else %}
        <a href="{{ path('login') }}">se connecter</a><br />
        <a href="{{ path('signup') }}">créer un compte</a>
{% endif %}

回答1:

You can extend firewall to all application by modifying pattern to ^/ and allow anonymous access 'anonymous' => true. Paths that should be secure specify in security.access_rules

$app->register(new Silex\Provider\SecurityServiceProvider(), array(
    'security.firewalls' => array(
        'account' => array(
            'pattern' => '^/',
            'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
            'users' => $app->share(function () use ($app) {
                return new UserProvider($app['db']);
            }),
            'anonymous' => true,
        )
    )
));

$app['security.access_rules'] = array(
    array('^/account', 'ROLE_USER', null)
);

User method getRoles() should return role ROLE_USER that means that user has access to all paths from security.access_rules with role ROLE_USER.

class User implements \Symfony\Component\Security\Core\User\AdvancedUserInterface
{
...
    public function getRoles()
    {
        return array(new \Symfony\Component\Security\Core\Role\Role('ROLE_USER'));
    }
...
}