Http Basic Authentication in Asp.Net Core Projects

Georg Dangl by Georg Dangl in Web Development Thursday, March 23, 2017

Thursday, March 23, 2017

Http Basic Authentication in Asp.Net Core Projects
Posted in DotNet SSL

There are many different ways how requests to an Asp.Net Core web application can be authenticated. Asp.Net Core Identity offers a great built in identity provider with some options for authentication, but there's no built in support for Http Basic authentication. The Microsoft docs for the old Web Api framework have a bit of background information about the disadvantages of Http Basic Authentication, especially that credentials are being sent with every request. Generally, it's not a great idea to support it, but unfortunately, you can't always enforce it when there are dependent services of your application. To support the Http Basic Authentication scheme, you've got to insert a small middleware in your app that validates Authorization headers, which can be done with the following code. I've split it up into a few classes to be more readable and easy to test, but here you go:

The BasicAuthenticationMiddleware checks if there's already an authenticated user for the request and if not, checks for Http Basic Authentication and tries to set the user identity for this request.

Http Basic headers are, essentially, passed as Base64("Username":"Password")BasicAuthenticationHeaderValue decodes that.

A wrapper to perform the actual sign in action for the user. It's not persisting the login via, for example, a cookie.

The MiddlewareExtensions just give you a nicer syntax to add the middleware to your Startup class.

Just remember that when using this, there is absolutely no way you can use unencrypted traffic! While unencrypted login pages themselves are bad enough (just ask devGeorge), Http Basic sends the username and password with every request. This makes eavesdropping so much more likely since any intercepted request now contains your full login data. Just use Let's Encrypt. While you're at it, use it everywhere. Use it for your staging environment. Use it for static pages hosting demos. Really, use encryption! Make the lock 🔒 in the browser bar your minimum requirement for every website. And educate your users to stop requiring Http Basic.

Otherwise, happy authenticating!


Share this post


comments powered by Disqus

About me

Hi, my name's George! I love coding and blogging about it. I focus on all things around .Net, Web Development and DevOps.

DanglIT

Need a consultant for BIM, GAEB or Software Development?

Contact me at [email protected], +49 (173) 56 45 689 or visit my professional page!

Dangl.Blog();
// Just 💗 Coding

Social Links