{"id":1503,"date":"2015-08-25T13:10:48","date_gmt":"2015-08-25T13:10:48","guid":{"rendered":"https:\/\/intelligentbee.com\/blog\/?p=1503"},"modified":"2024-10-25T09:12:21","modified_gmt":"2024-10-25T09:12:21","slug":"how-to-fix-symfony2-ajax-login-redirect","status":"publish","type":"post","link":"https:\/\/intelligentbee.com\/blog\/how-to-fix-symfony2-ajax-login-redirect\/","title":{"rendered":"How to Fix Symfony2 Ajax Login Redirect"},"content":{"rendered":"<p>You probably noticed that sometimes an Ajax request will return the login page\u00a0instead 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).<\/p>\n<h2>How to Fix Symfony2 Ajax Login Redirect<\/h2>\n<p>Here&#8217;s a quick way to fix this: we will create an event listener that will catch this authentication exception, check\u00a0for 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.<\/p>\n<p>Here&#8217;s the Symfony2 event listener:<\/p>\n<pre class=\"lang:php decode:true \">&lt;?php\r\n\/\/ src\/AppBundle\/EventListener\/AjaxAuthenticationListener.php\r\n\r\nnamespace AppBundle\\EventListener;\r\n\r\nuse Symfony\\Component\\HttpFoundation\\Response;\r\nuse Symfony\\Component\\Security\\Core\\Exception\\AuthenticationException;\r\nuse Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException;\r\nuse Symfony\\Component\\HttpKernel\\Event\\GetResponseForExceptionEvent;\r\n\/**\r\n *\/\r\nclass AjaxAuthenticationListener\r\n{\r\n\r\n    \/**\r\n     * Handles security related exceptions.\r\n     *\r\n     * @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance\r\n     *\/\r\n    public function onCoreException(GetResponseForExceptionEvent $event)\r\n    {\r\n        $exception = $event-&gt;getException();\r\n        $request = $event-&gt;getRequest();\r\n\r\n        if ($request-&gt;isXmlHttpRequest()) {\r\n            if ($exception instanceof AuthenticationException || $exception instanceof AccessDeniedException) {\r\n                $event-&gt;setResponse(new Response('', 403));\r\n            }\r\n        }\r\n    }\r\n}<\/pre>\n<p>As always, we will have to register it as a service:<\/p>\n<pre class=\"lang:yaml decode:true \">services:\r\n    ajax.authentication.listener:\r\n        class: AppBundle\\EventListener\\AjaxAuthenticationListener\r\n        tags:\r\n          - { name: kernel.event_listener, event: kernel.exception, method: onCoreException, priority: 1000 }<\/pre>\n<p>&nbsp;<\/p>\n<h3>How to Fix Symfony2 Ajax Login Redirect<\/h3>\n<p>In the\u00a0JavaScript 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\u00a0no longer authenticated.<\/p>\n<pre class=\"lang:js decode:true \">$(document).ready(function() {\r\n    $(document).ajaxError(function (event, jqXHR) {\r\n        if (403 === jqXHR.status) {\r\n            window.location.reload();\r\n        }\r\n    });\r\n});<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>You probably noticed that sometimes an Ajax request will return the login page\u00a0instead of the actual content is should return. [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":1173,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73,82],"tags":[194,238],"yst_prominent_words":[6,292,343,351,394,569,629,1084,2126],"post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1503"}],"collection":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/comments?post=1503"}],"version-history":[{"count":3,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1503\/revisions"}],"predecessor-version":[{"id":133278,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1503\/revisions\/133278"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/media\/1173"}],"wp:attachment":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/media?parent=1503"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/categories?post=1503"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/tags?post=1503"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/yst_prominent_words?post=1503"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}