Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AJAX auth errors listener for Symfony2
<?php
namespace Application\ProdrepHelperBundle\Component\Event;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
/**
*/
class AjaxAuthenticationListener
{
/**
* Handles security related exceptions.
*
* @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance
*/
public function onCoreException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$request = $event->getRequest();
if ($request->isXmlHttpRequest()) {
if ($exception instanceof AuthenticationException || $exception instanceof AccessDeniedException) {
$event->setResponse(new Response('', 403));
}
}
}
}
$(document).ready(function() {
$(document).ajaxError(function (event, jqXHR) {
if (403 === jqXHR.status) {
window.location.reload();
}
});
});
@semateos
Copy link

semateos commented Apr 30, 2012

Can you describe how you hook this event listener into symfony? I'm assuming it's in the service configuration - but I'm not clear on the details.

Loading

@semateos
Copy link

semateos commented May 1, 2012

// config.yml
services:
    ajax.listener:
        class: Application\ProdrepHelperBundle\Component\Event\AjaxAuthenticationListener
        tags:
          - { name: kernel.event_listener, event: kernel.exception, method: onCoreException, priority: 1000 }

Loading

@klaascuvelier
Copy link

klaascuvelier commented Feb 20, 2013

Very useful gist. Thank you very much.

Loading

@natestone
Copy link

natestone commented Mar 30, 2013

Agreed. Very helpful gist. Thank you.

Loading

@natorojr
Copy link

natorojr commented Apr 10, 2013

This information was extremely helpful. Thanks!

Loading

@sergio-toro
Copy link

sergio-toro commented Sep 4, 2013

Thank you! Really helpful gist.

Loading

@naitsirch
Copy link

naitsirch commented Jun 17, 2014

And if you want to register an error handler for AngularJS you can achieve this with this module

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');
    })
;

Include this angular module and the event handler just by dependency injection in your AngularJS app.

angular.module('myApp', ['nait.http_authentication']);

Loading

@RowanReid
Copy link

RowanReid commented Mar 6, 2015

This is a really helpful Gist! One question though - would it not be pertinent to implement a distinction between the user not being logged in VS being logged in and not having permission to access the URL requested?

Currently, if the user performs an Ajax request to a URL for which they are not authorised then they would experience a page reload which would not be ideal.

Loading

@paali
Copy link

paali commented Dec 11, 2015

Thank you! If anyone would just have an easy solution for global error handling (of just authentication/authorization errors) for superagent...

Loading

@anujeetphj
Copy link

anujeetphj commented Aug 12, 2016

I am implementing the same solution, I am using jquery Datatables in my application. When I return 403 error, before logging out, it gives a jquery error in alert, and when user clicks OK, session logs out.

Is there a way to do it without that alert coming??

Loading

@ohartl
Copy link

ohartl commented Apr 17, 2019

Note that returning it should return an http code 401 instead to be conform with the http standard

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment