How to stop perfoming on XHR requests when the user is logout in Symfony?

独自空忆成欢 提交于 2019-12-11 05:58:04

问题


Suppose I have opened my project in 2 different window and I logout using one of the window or you can say session is timed-out/expired (any one of the situation). After that in another window I am able to perform XHR requests when session is destroyed.

To over come this I have searched a lot and implemented some of it. I added a event listener but it did not worked.

namespace Webkul\CampusConnect\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Webkul\CampusConnect\EventListener\AjaxAuthenticationListener;

class AjaxAuthenticationListener
{

    /**
     * Handles security related exceptions.
     *
     * @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance
     */
    public function onCoreException(GetResponseForExceptionEvent $event)
    {
        dump('saurabh');
        die;
        $exception = $event->getException();
        $request = $event->getRequest();

        if ($request->isXmlHttpRequest()) {
            if ($exception instanceof AuthenticationException || $exception instanceof AccessDeniedException) {
                $event->setResponse(new Response('', 403));
            }
        }
    }
}

Service.yaml

ajax.authentication.listener:
        class: Webkul\CampusConnect\EventListener\AjaxAuthenticationListener
        tags:
          - { name: kernel.event_listener, event: kernel.exception, method: onCoreException, priority: 1000 }

Javascript

$(document).ready(function() {
$(document).ajaxError(function (event, jqXHR) {
if (403 === jqXHR.status) {
window.location.reload();
}
});
});

How can I stop performing XHR request when user is logged-out?


回答1:


Seems that because your priority is set up to 1000, default listener also runs and responses with a redirect to to login page (which ajax sees - https://stackoverflow.com/a/33578947/9358736). When you change your priority to -1000 then it should work (should, because it depends a lot of your application configuration). You can test it by just adding plain PHP code before $event->setResponse:

http_response_code(403);
die('Forbidden');


来源:https://stackoverflow.com/questions/56255053/how-to-stop-perfoming-on-xhr-requests-when-the-user-is-logout-in-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!