Silex - access to user outside a secured area

这一生的挚爱 提交于 2019-12-12 01:36:39

问题


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'));
    }
...
}


来源:https://stackoverflow.com/questions/36619957/silex-access-to-user-outside-a-secured-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!