Authentication can be achieved with API Key with multiple ways let see two different ways which are by using Middleware and Authentication Filters.
Authenticating API with Middleware
We need to create a middle ware class for Api middleware authentication.
Below example will show how to create a middle ware and how to use the same.
ApiKeyAuthMiddleware.cs
namespace CoreAPI.Authentication
{
public class ApiKeyAuthMiddleware
{
public readonly RequestDelegate _next;
public readonly IConfiguration _configuration;
public ApiKeyAuthMiddleware(RequestDelegate next,
IConfiguration configuration)
{
_next = next;
_configuration = configuration;
}
public async Task InvokeAsync(HttpContext context)
{
if(!context.Request.Headers.TryGetValue(AuthConstants.ApiKeyHeaderName,
out var extractedKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API Key is missing");
return;
}
var apiKey = _configuration.GetValue<string>(
AuthConstants.ApiKeySectionName);
if (!apiKey.Equals(extractedKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Invalid API Key");
return;
}
await _next(context);
}
}
}
AuthConstants.cs
namespace CoreAPI.Authentication
{
public class AuthConstants
{
public static string ApiKeyHeaderName = "x-api-key";
public static string ApiKeySectionName = "Authentication:APIKey";
}
}
Program.cs
using CoreAPI.Authentication;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// Adding Middleware
app.UseMiddleware<ApiKeyAuthMiddleware>();
app.UseAuthorization();
app.MapControllers();
app.Run();
appsettings.json
{
"Authentication": {
"APIKey": "12345678910"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
namespace CoreAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild",
"Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
Postman Output for the above code:
Authenticating API with Authorization Filter
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CoreAPI.Authentication
{
public class ApiKeyAuthFilter:IAuthorizationFilter
{
private readonly IConfiguration _configuration;
public ApiKeyAuthFilter(IConfiguration configuration)
{
_configuration = configuration;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
if (!context.HttpContext.Request.Headers.TryGetValue(
AuthConstants.ApiKeyHeaderName, out var extractedKey))
{
context.Result = new UnauthorizedObjectResult("API Key Missing");
return;
}
var apiKey = _configuration.GetValue<string>(
AuthConstants.ApiKeySectionName);
if (!apiKey.Equals(extractedKey))
{
context.Result = new UnauthorizedObjectResult("Invalid Api Key");
return;
}
}
}
}
AuthConstants.cs
namespace CoreAPI.Authentication
{
public class AuthConstants
{
public static string ApiKeyHeaderName = "x-api-key";
public static string ApiKeySectionName = "Authentication:APIKey";
}
}
Program.cs
using CoreAPI.Authentication;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(x=>x.Filters.Add<ApiKeyAuthFilter>());
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// Adding Middleware
//app.UseMiddleware<ApiKeyAuthMiddleware>();
app.UseAuthorization();
app.MapControllers();
app.Run();
appsettings.json
{
"Authentication": {
"APIKey": "12345678910"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
namespace CoreAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild",
"Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}