cakephpcakephp-3.2cakephp-3.1cakephp-3.3cakephp-3.4

Login redirecting in cakePHP 3.4


I'm trying to redirect to current page after logged in, using cakephp 3.4 but I'm getting like this

localhost page isn't working, locahost page redirecting you too many times. Try clearing your cookies

for 2 sec after that it's redirecting to home page. Please help me out here. Here my code

In appController.php

public function initialize()
{ 
    parent::initialize();
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authorize' => ['Controller'],
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ],
                'scope' => ['userStatus' => '1']
            ]
        ],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'unauthorizedRedirect' => $this->referer(),
        'logoutRedirect'       => [
                'controller' => 'Users',
                'action'     => 'login'
        ]
    ]);
}

In loginController.php

function login{ 
 if ( $this->request->is( 'post' ) ) {
    if ( $this->Auth->login() ) 
    {
       $this->redirect($this->referer());
    } 
    else {
      $this->Flash->error(__('Your username or password is incorrect.'));
    }
  }
}

Solution

  • Looks like you got some redirect loop here. You should use AuthComponent::redirectUrl().

    public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
    
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            } else {
                $this->Flash->error(__('Username or password is incorrect'));
            }
        }
    }
    

    See the Redirecting Users After Login in the Documentation.

    After logging a user in, you’ll generally want to redirect them back to where they came from. Pass a URL in to set the destination a user should be redirected to after logging in.

    If no parameter is passed, the returned URL will use the following rules:

    • Returns the normalized URL from the redirect query string value if it is present and for the same domain the current app is running on. Before 3.4.0, the Auth.redirect session value was used.
    • If there is no query string/session value and there is a config loginRedirect, the loginRedirect value is returned.
    • If there is no redirect value and no loginRedirect, / is returned.