Is there a symfony2 event / handler for aka session timeout not logged in

I am using FOSRestBundle to create ajax json calls inside the firewall. Everything seems to be working fine, except that Im was not able to process when the session timeout occurred. Right now, it is redirecting to login_check in this script, returning html to the client, not json.

I know and use the success_handler and fail_handler app in my application. I cannot find a built-in handler for dealing with authorization errors, such as session timeout.

Is there something inside the FOSRestBundle that can help solve this problem, or something that I don't see in Symfony2?

+6
source share
2 answers

Yes, Symfony offers the ability to handle exceptions. You must create an event listener that monitors the kernel.exception event with high priority. Create an event handler as follows:

 <?php namespace Acme\Bundle\MyBundle\EventListener; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\Exception\AuthenticationException; class AjaxAuthenticationListener { public function onKernelException(GetResponseForExceptionEvent $event) { $request = $event->getRequest(); $format = $request->getRequestFormat(); $exception = $event->getException(); if ('json' !== $format || (!$exception instanceof AuthenticationException && !$exception instanceof AccessDeniedException)) { return; } $response = new JsonResponse($this->translator->trans($exception->getMessage()), $exception->getCode()); $event->setResponse($response); $event->stopPropagation(); } } 

Now you need to register the event handler in one of your service.yml, for example:

 kernel.listener.ajax_authentication_listener: class: Acme\Bundle\MyBundle\EventListener\AjaxAuthenticationListener tags: - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 250 } 

Note the priority parameter used to tell Symfony to execute the handler before its own handlers, which have a lower priority.

And on your interface, you can register an event handler for jQuery, which reloads the page with such an error.

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

See this option for reference.

+5
source

I'm not sure if there is anything explicitly inside the FOSRest package, but Symfony2 itself is able to handle session timeouts.

Have you tried looking here? http://symfony.com/doc/current/components/http_foundation/session_configuration.html

0
source

Source: https://habr.com/ru/post/915673/


All Articles