简体   繁体   中英

How to redirect “Access denied” to login page in Silex

This is my firewall code

$app['security.firewalls']=[
    'secured'=>[
        'pattern' => '/',
        'anonymous' => true,
        'http'=>true,
        'form' => array('login_path' => '/login', 'check_path' => '/secured/login_check'),
        'logout' => array('logout_path' => '/secured/logout', 'invalidate_session' => true),
        'users'=>$users
    ]
];
$app['security.access_rules']=[
    ["^/admin", "ROLE_ADMIN"]
];

When users access admin page without role admin, how to redirect them to login page?

I have test with no access rules in admin controller code:

if($app['security.authorization_checker']->isGranted('ROLE_ADMIN')){
        // ...
        // ...
        // ...
    }
else return $app->redirect($app->url('login'));

But the problem when I use this method is that it will redirect to homepage instead of previous page. How can I make login page to redirect to previous page instead of homepage after successful login check?

Try to add always_use_default_target_path and use_referer parameters to security config:

$app['security.firewalls']=[
    'secured'=>[
         ...
        'form' => array(
            'login_path' => '/login',
            'check_path' => '/secured/login_check',
            'always_use_default_target_path' => false,
            'use_referer' => true
        ),
         ...
    ]
];

Why do you use 2 entry points for login? http and form ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM