Preventing HTTP Basic Auth Dialog using AngularJS Interceptors

All we need is an easy explanation of the problem, so here it is.

I’m building an AngularJS (1.2.16) web app with a RESTful API, and I’d like to send 401 Unauthorized responses for requests where authentication information is invalid or not present. When I do so, even with an HTTP interceptor present, I see the browser-presented basic “Authentication Required” dialog when an AJAX request is made via AngularJS. My interceptor runs after that dialog, which is too late to do something useful.

A concrete example:

My backend API returns 401 for /api/things unless an authorization token is present. Nice and simple.

On the AngularJS app side, I’ve looked at the docs and set up an interceptor like this in the config block:

$httpProvider.interceptors.push(['$q', function ($q) {
  return {
    'responseError': function (rejection) {
      if (rejection.status === 401) {
        console.log('Got a 401')
      }
      return $q.reject(rejection)
    }
  }
}])

When I load my app, remove the authentication token, and perform an AJAX call to /api/things (to hopefully trigger the above interceptor), I see this:

Authentication Required

If I cancel that dialog, I see the console.log output of “Got a 401” that I was hoping to see instead of that dialog:

Got a 401

Clearly, the interceptor is working, but it’s intercepting too late!

I see numerous posts on the web regarding authentication with AngularJS in situations just like this, and they all seem to use HTTP interceptors, but none of them mention the basic auth dialog popping up. Some erroneous thoughts I had for its appearance included:

  • Missing Content-Type: application/json header on the response? Nope, it’s there.
  • Need to return something other than promise rejection? That code always runs after the dialog, no matter what gets returned.

Am I missing some setup step or using the interceptor incorrectly?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Figured it out!

The trick was to send a WWW-Authenticate response header of some value other than Basic. You can then capture the 401 with a basic $http interceptor, or something even more clever like angular-http-auth.

Method 2

I had this issue together with Spring Boot Security (HTTP basic), and since Angular 1.3 you have to set $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; for the popup not to appear.

Method 3

For future reference

I’ve come up with this solution when trying to handle 401 errors.
I didn’t have the option to rewrite Basic to x-Basic or anything similar, so I’ve decided to handle it on client side with Angular.

When initiating a logout, first try making a bad request with a fake user to throw away the currently cached credentials.

I have this function doing the requests (it’s using jquery’s $.ajax with disabled asynch calls):

function authenticateUser(username, hash) {
    var result = false;
    var encoded = btoa(username + ':' + hash);

    $.ajax({
        type: "POST",
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", 'Basic ' + encoded);
        },
        url: "user/current",
        statusCode: {
            401: function () {
                result = false;
            },
            200: function (response) {
                result = response;
            }
        },
        async: false
    });

    return result;
}

So when I try to log a user out, this happens:

//This will send a request with a non-existant user.
//The purpose is to overwrite the cached data with something else
accountServices.authenticateUser('logout','logout');

//Since setting headers.common.Authorization = '' will still send some
//kind of auth data, I've redefined the headers.common object to get
//rid of the Authorization property
$http.defaults.headers.common = {Accept: "application/json, text/plain, */*"};

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply