当用户在 Symfony 中注销时,如何停止执行 XHR 请求? [英] How to stop perfoming on XHR requests when the user is logout in Symfony?

查看:51
本文介绍了当用户在 Symfony 中注销时,如何停止执行 XHR 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 2 个不同的窗口中打开了我的项目,并且我使用其中一个窗口注销,或者您可以说会话超时/过期(任何一种情况).之后在另一个窗口中,当会话被销毁时,我可以执行 XHR 请求.

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();
}
});
});

如何在用户注销时停止执行 XHR 请求?

推荐答案

似乎因为您的优先级设置为 1000,默认侦听器也会运行并响应重定向到登录页面(ajax 看到的 - https://stackoverflow.com/a/33578947/9358736).当您将优先级更改为 -1000 时,它应该可以工作(应该可以,因为这在很大程度上取决于您的应用程序配置).您可以通过在 $event->setResponse 之前添加纯 PHP 代码来测试它:

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');

这篇关于当用户在 Symfony 中注销时,如何停止执行 XHR 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆