We need to authenticate users/clients that are going to use our APIs.

For this we need to add a middleware that will do this for every API call.

Okay so for this we need a key. Generate any random string not easy to generate again and add this in appsettings.json file.


Now create a new folder named "Middleware" and add a .cs file "APIKeyMiddleware.cs". Now add the following code:

using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; namespace AGGWebAPI.Middleware { public class ApiKeyMiddleware { private readonly RequestDelegate _next; private const string APIKEYNAME = "APIKey"; public ApiKeyMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { if (!context.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey)) { context.Response.StatusCode = 401; await context.Response.WriteAsync("Api Key was not provided"); return; } var appSettings = context.RequestServices.GetRequiredService<IConfiguration>(); var apiKey = appSettings.GetValue<string>(APIKEYNAME); if (!apiKey.Equals(extractedApiKey)) { context.Response.StatusCode = 401; await context.Response.WriteAsync("Unauthorized client."); return; } await _next(context); } } } code-box

Now we need to register this Middleware. Add following code in Porgrame.cs after this method "app.UseAuthorization();"


Now we are ready to test the API on Postman.

Note: In hearder tab in the Postman now you have to write the API Key:

For more details and theory check this article.

Post a Comment

Previous Post Next Post