Trouble with Auth Component failing to redirect to previous page

After near two hours of cycling through my code and the CakePHP API documents to find out why CakePHP was redirecting to my $this->Auth->loginRedirect instead of the $this->Auth->redirectUrl(), I finally stumbled on a similar case by someone in the CakePHP ticketing system

It turned out that there was no mention of the way the Auth Component worked in the new version of CakePHP.

I had tried getting back to the previous page I tried to access when not logged in, but CakePHP kept sending me to the default URL I specified for login redirect.

The solution I eventually found out was to ensure that I did the redirect in my login method – duh!

But that was not the only caveat. In order to redirect to the previously requested page, you must by no means make a call to $this->Auth->redirectUrl() anywhere other than when doing the redirect.

If for any reason you try to save the URL from $this->Auth->redirectUrl() in a variable and your page redirects, that variable is lost along with the content of $this->Auth->redirectUrl().

For this reason, you application will only be able to redirect you to a default URL which is what CakePHP does eventually.

Thank God I found out that the value obtained from $this->Auth->redirectUrl() is erased immediately after that method is called.

So if you are having the same issue, it might be best to call “$this->Auth->redirectUrl()”  inside your call to $this->redirect().

So you would end up with something like:


Now that’s just a piece of cake.


3 thoughts on “Trouble with Auth Component failing to redirect to previous page

  1. Thanks – this is a great help. And if you, like me, need to read the value returned by $this->Auth->redirectUrl() without erasing it, you can find it using $this->Session->read(‘Auth.redirect’) instead 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s