Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to register an Symfony event handler to prevent JSON/AJAX requests to be redirected
<?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();
}
}
// for jQuery
$(document).ready(function() {
$(document).ajaxError(function (event, jqXHR) {
if (403 === jqXHR.status) {
window.location.reload();
}
});
});
// for AngularJS
angular
.module('nait.http_authentication', [])
.config(function ($httpProvider, $provide) {
$provide.factory('naitHttpAuthenticationInterceptor', function($q) {
return {
'responseError': function(rejection) {
if (403 === rejection.status) {
window.location.reload();
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('naitHttpAuthenticationInterceptor');
})
;
angular.module('myApp', ['nait.http_authentication']);
services:
kernel.listener.ajax_authentication_listener:
class: Acme\Bundle\MyBundle\EventListener\AjaxAuthenticationListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 250 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment