In this article, we're going to create the code (and understand how it works) to handle API Key authentication with just three lines of code extending the native Authentication mechanism. We want a 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 ourself's 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.
Introduction
The native implementation of ASP.NET Authentication allows us to extend it and create our validation logic. With the AddScheme builder, we're going to implement the APIKey Authentication.
Everything begins with the services.AddAuthentication code. This builder provides 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 configurations of our ApiKeyAuthN service, such as the QueryStringKey and ApiKey.
The second step is the file ApiKeyAuthN.cswith the following content.
The class AuthenticationHandler is responsible for 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 implementation 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.
Wrapping 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 set up the Configure method to use Authentication and Authorization middlewares.
We also added WriteClaims method to see the user's Claims.
Let's run it.
Without API Key
With API Key added
Making it easier to use
Let's create an extension method builder for our AddApiKey handler. Create the file ApiKeyAuthNExtensions.cs with the following contents.
This adds the extension method AddApiKey instead of calling AddScheme. Change the Configure method in Startup class to use the new method.