laravel/laravel — pull request #2399 by JosephSilber (2013-11-04 02:18:24+00:00)
Title: Auth should respond with a 401 to AJAX requests

When using the Auth filter, if the user is not authenticated we currently redirect them to the login route.

If the request was an AJAX request, redirecting to an HTML form makes no sense. Instead, we should return a 401 unauthorized header, so that the client code can listen for that and do its own redirection/authentication.

---

Here's some sample code I use with jQuery:

$.ajaxSetup({
statusCode: {
401: function () {
window.location = '/login';
}
}
});

And here's some sample code that I use with AngularJS:

// angular doesn't automatically set the X-Requested-With header
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

// Redirect AJAX calls that return a 401 status code
$httpProvider.responseInterceptors.push(function ()
{
return function ( promise )
{
return promise.then(function ( response )
{
return response;
},
function ( response )
{
if ( response.status == 401 ) window.location.reload();
});
}
});

This angular app uses html5mode single page navigation, so that the new request to the same route will be redirected to `login` with `::intended()`, and would then be redirected back to the requested URL. Sweet.