July 04 2024
[ApiKey]
[HttpGet(Name = "GetAllUsers")]
public List<string> GetAll()
{
return new List<string> { "Stefan" };
}
public class ApiKeyAttribute : ServiceFilterAttribute
{
public ApiKeyAttribute() : base(typeof(ApiKeyAuthorizationFilter))
}
public class ApiKeyAuthorizationFilter : IAuthorizationFilter
{
private const string ApiKeyHeaderName = "x-api-key";
private readonly IApiKeyValidator _apiKeyValidator;
public ApiKeyAuthorizationFilter(IApiKeyValidatior apiKeyValidator)
{
_apiKeyValidator = apiKeyValidator;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
string apiKey = context.HttpContext.Request.Headers[ApiKeyHeaderName];
if(!_apiKeyValidator.IsValid(apiKey))
{
context.Result = new UnauthorizedResult();
}
}
}
var apiKey = context.HttpContext.Request.Headers[ApiKeyHeaderName];
public class ApiKeyValidator : IApiKeyValidator
{
public bool IsValid(string apiKey)
{
//Change logic for validation api key
return false;
}
}
public interface IApiKeyValidator
{
bool IsValid(string apiKey);
}
builder.Services.AddSingleton<ApiKeyAuthorizationFilter>();
builder.Services.AddSingleton<IApiKeyValidator, ApiKeyValidator>();
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string ApiKeyHeaderName = "x-api-key";
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if(!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Api Key was not provided.");
return;
}
if(extractedApiKey != "API_KEY")
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized.");
return;
}
await _next(context);
}
}
1. Design Patterns that Deliver
This isn’t just another design patterns book. Dive into real-world examples and practical solutions to real problems in real applications.Check out it here.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Join 15,250+ subscribers to improve your .NET Knowledge.
Subscribe to the TheCodeMan.net and be among the 15,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.