SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

CakePHP Auth redirecting issue

When working with CakePHP's Auth component, we had an issue, which is Auth component does not redirect page properly. After debugging for some time, we found the cause and we think it is worth sharing here. Hopefully it will help you if you encounter an issue similar.


Basically we want to use CakePHP's Auth component to authenticate user. After user succesfully logins in, we want to record its login time. So in our beforeFilter() function we set autoRedirect to FALSE

function beforeFilter() {
    //set up Auth component    
    $this->Auth->autoRedirect = FALSE;

And then in UsersController's login() function, we use following script to update user's login time:

function login() {
    //-- code inside this function will execute only when autoRedirect was set to false (i.e. in a beforeFilter).
    if (!(empty($this->data)) && $this->Auth->user()) {
        $this->User->id = $this->Auth->user('id');
        $this->User->saveField('last_login', date('Y-m-d H:i:s') );

Ok, did you spot the mistake we made. If yes, then you must know we are doing something wrong. However we did not notice at the first place. So everytime after we successfully login, Auth component redirects us to the front page of our website. It means it never remebers where we wanted to go before we login. However as mentioned in CakePHP's Cookbook:

The AuthComponent remembers what controller/action pair you were trying to get to before you were asked to authenticate yourself by storing this value in the Session, under the Auth.redirect key. ...


The mistake we made here is that we called $this->Auth->redirect() before we rediret our page. Because $this->Auth->redirect() function will return the URL we were going and then set it to null. So by doing below, we actually set Auth.redirect to be null:

function login() {     

As soon as we commented out this log function, our application worked.

The end

Hopefully this simple tip helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.