weixin_33735077 2015-11-03 20:26 采纳率: 0%
浏览 37

Session Expire Symfony 2 Ajax

My application uses ajax to request data. I'm using Symfony2, and when the session expires and I make a request with ajax, the login form is shown inside the main area on my application, and not as another view as should be. How can solve this problem. Thanks

  • 写回答

2条回答 默认 最新

  • weixin_33743703 2015-11-03 20:45
    关注

    I would suggest creating event listener which will be listening for every request:

    services.yml:

    your_request_listener:
        class: Acme\AppBundle\EventListener\RequestListener
        arguments: [@security.token_storage]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onRequest }
    

    In this event listener I would check for type of request so this would be only Ajax request listener. When request is ajax type then I would check if session has expired - if so, I would create response which will be valid response for ajax request (i.e. JsonResponse) and set this response to be sent to user.

    class RequestListener
    {
        private $tokenStorage;
    
        public function __construct(TokenStorageInterface $tokenStorage)
        {
            $this->tokenStorage = $tokenStorage;
        }
    
        public function onRequest(GetResponseEvent $event)
        {
            $request = $event->getRequest();
            if (!$request->isXmlHttpRequest()) {
                return; //we dismiss requests other than ajax
            }
    
            //now you check if user is authenticated/session expired/whatever you need
            $token = $this->tokenStorage->getToken();
            if ($token === null) {
                //now you create response which you would expect in your js doing ajax, for example JsonResponse
                $response = new JsonResponse(); //you should give some content here
                $event->setResponse($response); //now you override response which will be sent to user
            }
    
        }
    }
    
    评论

报告相同问题?