This post is about how implement basic authentication in ASP.NET Core Minimal API. Few days back I got a question / comment in the blog post about Minimal APIs - about implementing Basic authentication in Minimal APIs. Since the Action Filters support is not available in Minimal API I had to find some alternative approach for the implementation. I already wrote two blog posts Basic authentication middleware for ASP.NET 5 and Basic HTTP authentication in ASP.Net Web API on implementing Basic authentication. In this post I am implementing an AuthenticationHandler and using this for implementing basic authentication. As I already explained enough about the concepts, I am not discussing them again in this post.
Here is the implementation of the BasicAuthenticationHandler which implements the abstract class AuthenticationHandler.
Next modify the Program.cs like this.
Now it is done. You can enable block the anonymous access by adding the authorize attribute to the method like this.
Now if you browse the Weather forecast endpoint - https://localhost:5001/weatherforecast, it will prompt for user name and password. Here is the screenshot of the app running on my machine.