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
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.
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:
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: