Skip to content

Instantly share code, notes, and snippets.

@romaricdrigon
Created August 21, 2013 07:13
Show Gist options
  • Save romaricdrigon/6291210 to your computer and use it in GitHub Desktop.
Save romaricdrigon/6291210 to your computer and use it in GitHub Desktop.
Symfony2 + AngularJS de-authentification handling
var app = angular.module('nav', [])
/*
Finally, we add to our module configuration an Interceptor.
This function will be called every time a request is made using $http or higher level services ($resource...).
This code is for Angular 1.0.7, it seems $httpProvider.responseInterceptors is deprecated in 1.1.X (but still working).
Consider using Interceptors in 1.1.X, http://docs.angularjs.org/api/ng.$http
*/
.config(function($httpProvider) {
function loginInterceptor($q, $window) {
function success(response) {
return response;
}
function error(response) {
if (response.status == 401) {
// refresh page if user is de-logged
$window.location.reload();
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}
$httpProvider.responseInterceptors.push(loginInterceptor);
})
;
<!-- services config file - declare our event subscriber -->
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme.listener.unauthorized_ajax" class="Acme\DemoBundle\EventListener\UnauthorizedAjaxListener">
<tag name="kernel.event_subscriber" />
</service>
</services>
</container>
<?php
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/*
By default, Symfony2 redirects unauthentificated requests, event XMLHttp ones (AJAX),
to the login form (302 redirects, AngularJS will automatically follow).
We make them send a 401 (unauthorized) error, so we can catch those in Javascript.
*/
class UnauthorizedAjaxListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
KernelEvents::EXCEPTION => array(
'onKernelException', 10
)
);
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$request = $event->getRequest();
// determine the actual cause for the exception
while (null !== $previous = $exception->getPrevious()) {
$exception = $previous;
}
// here is our custom logic
if ($exception instanceof AuthenticationException && $request->isXmlHttpRequest()) {
$event->setResponse(new Response('', 401));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment