Search code examples
phpsecuritysilex

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?


Solution

  • 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?