Skip to content

Instantly share code, notes, and snippets.

@stollr
Forked from xanf/AjaxAuthenticationListener.php
Last active August 29, 2015 14:02
Show Gist options
  • Save stollr/f1d3fff96c59fc43bd86 to your computer and use it in GitHub Desktop.
Save stollr/f1d3fff96c59fc43bd86 to your computer and use it in GitHub Desktop.
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