In this article we're going to create the code (and understand how it works) for handle API Key authentication with just three lines of code extending the native Authentication mechanism. We want the simple and stupid solution and not some crazy implementation using MVC[Attributes] or any customized middleware to handle the Authentication.
Ok, ok, ok. I know it's hard to find a good implementation of API Key Authentication out there on the internet. I think it's also hard to ourselfs needing of API Key Authentication on daily basis. But now you found it now! Hope you like it. Leave a comment :)
Disclaimer: Maybe I'm writing this article mad with someone hahahahaha. Please forgive me.
The native implementation of ASP.NET Authentication allow us to extend it and create our own validation logic. With the AddScheme builder we're going to implement the APIKey Authentication.
Everythin begins with the services.AddAuthentication code. This builder provide us the ability to use the method AddScheme. Here is where our Auth ApiKey handler goes.
Starting with the Code
Let's start by creating the file ApiKeyAuthNOptions.cs. This file will contain all configuration of our ApiKeyAuthN service, such as the QueryStringKey and ApiKey.
Second step is the file ApiKeyAuthN.cswith the following content.
The class AuthenticationHandler is responsable to making the validation and create the Authentication Ticket for the user.
I think you can guess where to put the validation logic, right? Here is the implementation.
The implentation of BuildPrincipal is up to you. You should customize the ClaimsIdentity with the Claims you find necessary in your application, such as Role, PhoneNumber, Issuer, Partner Id, among others.
Wraping thing up - We're almost there
We have everything we need to start the authentication. Open your Startup.cs file and add the following contents.
In AddScheme we're configuring the service to use our Authentication handler. Next setup the Configure method to use Authentication and Authorization middlewares.