Enabling Basic Authentication for Angular and jQuery clients for your ASP.NET WebApi

I have been working on a WebAPI for a client over the past few months and I’ve successfully implemented Basic authentication on my WebAPI and connected to it using a Xamarin Android client.

I’ve come to a point where I need to start supporting AngularJS clients, but I don’t like how the browsers each have their own default login dialogs that are ugly. I found a great blog entry solving this exact issue, but the author wrote their server side in Sinatra.

Here is the blog entry with the situation and solution:


You’ll need to implement Basic authentication on your WebAPI to make this work. To implement Basic authentication on your ASP.NET WebAPI, follow the instructions here:


One thing to make sure you do (in Web.config) is change the

type="WebHostBasicAuth.Modules.BasicAuthHttpModule, BasicAuth"

to reflect the project name and binary name of your project (your’s shouldn’t be named WebHostBasicAuth.Modules.BasicAuthHttpModule. It will be the name of your project instead.

type="{ProjectName}.Modules.BasicAuthHttpModule, {BinaryName}

It turns out that the changes required to make the solution outlined in Ole Friis Østergaard’s post is very easy to implement in ASP.NET.

Here is the code you need to change in the Basic Authentication Implementation from above:

// If the request was unauthorized, add the WWW-Authenticate header  
// to the response. 
private static void OnApplicationEndRequest(object sender, EventArgs e)  
    var response = HttpContext.Current.Response; 
    // see if the request sent an X-Requested-With header (Non-Browser request - 
    // used by jQuery and Angular implementations to prevent the browser from 
    // presenting the default Login dialog) 
    var request = HttpContext.Current.Request; 
    string authType = "Basic"; 
    if (response.StatusCode == 401) 
        if (request.Headers.AllKeys.Contains("X-Requested-With")) 
            if (request.Headers["X-Requested-With"] == "XMLHttpRequest") 
                authType = "xBasic"; 
        response.Headers.Add("WWW-Authenticate", string.Format("{0} realm="{1}"", authType, Realm));

That’s it! Now, when you pass in the X-Requested-With header value of "XMLHttpRequest", you’ll get back a WWW-Authenticate header with a type of “xBasic” instead of “Basic”. That will cause the browser to ignore the request and suppress the login dialog, letting you display your own pretty dialog.

I have started a GitHub project that has my Sample WebAPI in it. I’ll be updating that to include the AngularJS code as I create it to demonstrate exactly how to pull this off since Ole’s post is light on details.

Here is the GitHub project: