DEV Community

Cover image for How to Implement API Key Authentication in .NET 8
Duc Dang
Duc Dang

Posted on

How to Implement API Key Authentication in .NET 8

What is API Key Authentication in .NET 8?

Imagine you’ve developed a weather dashboard that fetches data from your own weather API. This dashboard displays real-time weather data, forecasts, and other information. However, you want to:

  • Limit Access: Ensure only authorized clients can access your API.
  • Track Usage: Monitor which clients are using your API, how often, and for what purposes.
  • Prevent Abuse: Protect your API from being spammed with requests, which could consume resources and potentially cost you money.
  • Commercialization: Monetize your API by implementing different pricing tiers for each client. By implementing API Key Authentication, you can secure your API to ensure it is used only in ways that you have explicitly allowed.

Step #1: Create ApiKeyAttribute

The ApiKeyAttributeclass derives from ServiceFilterAttributeand is used to decorate the controllers or actions where you want this specific authorization to take place.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiKeyAttribute : ServiceFilterAttribute
{
    public ApiKeyAttribute() : base(typeof(ApiKeyAuthorizationFilter))
    {
    }
}

Enter fullscreen mode Exit fullscreen mode

For example, you can decorate an endpoint like this:

[ApiKey]
[HttpGet(Name = "GetAllUsers")]
public List<string> GetAll()
{
    return new List<string> { "ducdang" };
}

Enter fullscreen mode Exit fullscreen mode

Step #2: Implement ApiKeyAuthorizationFilter

The ApiKeyAuthorizationFilterclass implements IAuthorizationFilter, which contains logic to execute when a request requires authorization. This filter checks if an API key is present and if it’s valid.

public class ApiKeyAuthorizationFilter : IAuthorizationFilter
{
    private const string ApiKeyHeaderName = "x-api-key";
    private readonly IApiKeyValidator _apiKeyValidator;

    public ApiKeyAuthorizationFilter(IApiKeyValidator apiKeyValidator)
    {
        _apiKeyValidator = apiKeyValidator;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var apiKey = context.HttpContext.Request.Headers[ApiKeyHeaderName];

        if (!_apiKeyValidator.IsValid(apiKey))
        {
            context.Result = new UnauthorizedResult();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Step #3: Implement ApiKeyValidator

The ApiKeyValidatorencapsulates the logic of how you will validate the API key received in the request.

public class ApiKeyValidator : IApiKeyValidator
{
    private readonly IConfiguration _configuration;
    private const string APIKEYNAME = "x-api-key";

    public ApiKeyValidator(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public bool IsValid(string apiKey)
    {
        var validApiKey = _configuration.GetValue<string>(APIKEYNAME);
        return apiKey == validApiKey;
    }
}

Enter fullscreen mode Exit fullscreen mode

API Endpoint Testing

Here’s how you can make a request to the secure endpoint using the API key:

curl -H "x-api-key: your-api-key-here" https://yourapi.com/api/secure

Enter fullscreen mode Exit fullscreen mode

For Middleware

You can also implement API Key Authentication using middleware for a more centralized approach.

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string APIKEY = "x-api-key";

    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(APIKEY, 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>(APIKEY);

        if (!apiKey.Equals(extractedApiKey))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Unauthorized client.");
            return;
        }

        await _next(context);
    }
}

Enter fullscreen mode Exit fullscreen mode

Register the middleware in Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware<ApiKeyMiddleware>();
    app.UseMvc();
}

Enter fullscreen mode Exit fullscreen mode

Wrapping Up

Implementing API Key Authentication in .NET 8 is a straightforward process that enhances the security of your APIs. By following the steps outlined above, you can ensure that only authorized clients can access your API endpoints.

Top comments (0)