Search code examples
cakephpcakephp-3.0cakephp-3.4

Redirect to referrer not working after Login


After logging a user in, I want to redirect them back to where they came from but It's not working properly in CakePHP 3.5. Here are the required info's to help me figure out this problem.

URL while login(session time out),

http://dev.scys.com/db/admin?redirect=%2Fadmin%2Fstatuses

This is my Auth config,

$this->loadComponent('Auth', [
            'loginAction' => ['controller' => 'Admins', 'action' => 'login'],
            'loginRedirect' => ['controller' => 'Admins', 'action' => 'index'],
            'logoutRedirect' => ['controller' => 'Admins', 'action' => 'login'],
            'unauthorizedRedirect' => $this->referer(),
            'authenticate' => [
                'Form' => [
                    'finder' => 'auth',
                    'userModel' => 'Admins',
                    'fields' => ['username' => 'username', 'password' => 'password']
                ]
            ]

        ]);

And in the Login method/action

$user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }

More Points

I have also tried $this->redirect($this->request->getQuery('redirect'));

Am I missing anything or something else I have to add to work this out :(


Solution

  • I figured out my mistake, Actually, I was using for action URL like,

    $this->Form->create(NULL, ['url'=> ['controller' => 'Admins', 'action' => 'login'],'style'=>'display: block;');
    

    Because of this, the URL became "admins/login" and the redirect query string get removed that's why the problem occurred, because "$this->redirect($this->Auth->redirectUrl());" didn't find any redirect query string(as per the case 1), so it uses $this->Auth->config('loginRedirect');(as per case 2).

    Then I solve it by removing the URL key and value from the form create option parameter.