-->

Silex: redirect admin to admin-home path after log

2019-06-04 08:09发布

问题:

How in Silex redirect admin (ROLE_ADMIN) to /admin page after successful login and user (ROLE_USER) to / page after successful login? My config so far:

$app['security.firewalls'] = array(
    '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) {
                 return new App\User\UserProvider($app['db']);
        }),
      ),
);
$app['security.access_rules'] = array(
array('^/admin', 'ROLE_ADMIN', 'http'),
    array('^.*$', 'ROLE_USER'),
);

Thx in advance

回答1:

I think there are a few ways to do this - I would recommend adding a new controller for /login/redirect and then sending people there after login. The controller can then perform the logic for where to send users based on their roles.

class LoginRedirect implements ControllerProviderInterface {

    public function connect(Application $app) {
        $controller = $app['controllers_factory'];
        $controller->get('/', array($this, 'index'))->bind('login-redirect');
        return $controller;
    }

    public function index(Application $app) {

        if ($app['security']->isGranted('ROLE_ADMIN')) {
            return $app->redirect($app['url_generator']->generate('admin-home'));
        }

        return $app->redirect($app['url_generator']->generate('non-admin-home'));
    }

}

Add a route for it:

$app->mount('/login/redirect', new Controller\LoginRedirect());

And then in your security firewall settings add the options in the form section to use this route as the default target path - i.e. where all users are redirected to after login. Note that with this setting, you will loose the feature where users are redirected to the HTTP referer.

...
    'form' => array(
        'login_path' => '/login',
        'check_path' => '/login_check',
        'always_use_default_target_path' => true,
        'default_target_path' => '/login/redirect'
    ),
...


标签: php login silex