Introduction
API key authentication will keep a secure line between the API and clients, however, if you wish to have user authentication, go with token-based authentication, aka OAuth2.0. In this article, you will learn how to implement the API Key Authentication to secure the ASP.NET Core Web API by creating a middleware.
API Key Authentication
Step 1
Open Visual Studio Create or open a ASP.NET Core Web API Project, in my case I’m creating a new project with .NET 6.
Creating a new project
Select a template as shown in the below figure
Step 2
Run the application and you will get swagger UI to access WeatherForecast API.
Step 3
Create a Middleware Folder, and add a new C# file. I named the new class as ApiKeyMiddleware.cs
ApiKeyMiddleware.cs
The middleware will check the API key in the header and validate the key by extracting it from the header and compare with the key defined in code.
InvokeAsync method is defined in this middleware so that it will contain the main process, in our case, the main process will be to search and validate the ApiKey header name and value within the httpcontext request headers collection
If there is no header with APIKEY it will return “Api Key was not provided”
Step 4
Open Program.cs file to register the middleware
Step 5
Open appsettings.json file and add an API Key
Step 6
Run the application, and test the API using POSTMAN without passing the ApiKey in header, you will get “Api Key was not provided” message in payload, as shown in the below figure.
Passing wrong API Key
Providing correct API Key
Happy Coding!!!
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.