-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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']); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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