Add APIKey authentication
This commit is contained in:
27
Helpers/ApiKeyAttribute.cs
Normal file
27
Helpers/ApiKeyAttribute.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace TodoApi.Helpers;
|
||||
|
||||
public class ApiKeyAttribute : ActionFilterAttribute
|
||||
{
|
||||
public override void OnActionExecuting(ActionExecutingContext context)
|
||||
{
|
||||
// Get the required service to validate the API key
|
||||
var apiKeyValidator = context.HttpContext.RequestServices.GetRequiredService<IApiKeyValidator>();
|
||||
|
||||
// Get the API key from the X-API-KEY header
|
||||
var apiKey = context.HttpContext.Request.Headers["X-API-KEY"];
|
||||
|
||||
// Validate the API key using the IApiKeyValidator service
|
||||
if (string.IsNullOrEmpty(apiKey) || !apiKeyValidator.Validate(apiKey))
|
||||
{
|
||||
// If the API key is invalid, set the response status code to 401 Unauthorized
|
||||
context.Result = new UnauthorizedResult();
|
||||
return;
|
||||
}
|
||||
|
||||
// If the API key is valid, continue with the action execution
|
||||
base.OnActionExecuting(context);
|
||||
}
|
||||
}
|
||||
20
Helpers/ApiKeyValidator.cs
Normal file
20
Helpers/ApiKeyValidator.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
namespace TodoApi.Helpers
|
||||
{
|
||||
public interface IApiKeyValidator
|
||||
{
|
||||
bool Validate(string? apiKey);
|
||||
}
|
||||
|
||||
public class ApiKeyValidator(List<string>? apiKeys) : IApiKeyValidator
|
||||
{
|
||||
private readonly List<string>? _apiKeys = apiKeys;
|
||||
|
||||
public bool Validate(string? apiKey)
|
||||
{
|
||||
if (_apiKeys == null) return false;
|
||||
|
||||
// Verify the provided apiKey is in our configuration
|
||||
return _apiKeys.Contains(apiKey!.ToLower());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user