visit our site

How to Fix Symfony2 Ajax Login Redirect

In Blog, PHP and Symfony

by Dragos Holban on August 25, 2015

You probably noticed that sometimes an Ajax request will return the login page instead of the actual content is should return. This happens when the user has beed logged out in the background and the current page does not reflect that (it could happen if the session expired or if the user simply logged out from another browser window/tab).

Here’s a quick way to fix this: we will create an event listener that will catch this authentication exception, check for an Ajax request and, if found, it will return a 403 http code instead of redirecting to the login page. The JavaScript code will then know to reload the page and thus redirect to login in case of 403 instead of loading and showing the received content to the user.

Here’s the Symfony2 event listener:

As always, we will have to register it as a service:

In the JavaScript code we add the following to make jQuery treat the Ajax errors by reloading the window in case of a 403 error. What will actually happen is that the user will end on the login page as he is no longer authenticated.

 

 

5 Replies to “How to Fix Symfony2 Ajax Login Redirect”

  1. Hey I know tthis is off topic but I was wondering if you knew of any
    widgets I could add to my blog that automatically
    twet my newest twitter updates. I’ve been looking for a plug-in like this for quite soke tie and was hoping maybe you would
    have soe experience wth something like this. Pleease let me know if
    you run into anything. I truly enjoy reading yoir blog and I
    look forward to your new updates.

  2. The alternative is to upgrade to the latest Symfony version. As of 2.6 or 2.7 (I don’t remember when we added it), requests detected as being AJAX ones (through the X-Requested-With header) are not redirected to the login page anymore.

    1. Hi Christophe! I just tested with Symfony 2.7. An AJAX call to a secured action redirected and returned the login page. Could you point me to the place where I can find more details about the feature you described above? Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

+1
Share
Tweet
Share
Stumble
Pin