---
title: "How do you implement API key authentication?"  
description: "How do you implement API key authentication?"  
author: "ICSM Computer"  
published: 2025-06-05  
updated: 2025-06-05  
canonical: https://www.mindstick.com/interview/34213/how-do-you-implement-api-key-authentication  
category: "api(s)"  
tags: ["api(s)", "authentication", "authorization"]  
reading_time: 4 minutes  

---

# How do you implement API key authentication?

API Key authentication is a **simple, stateless** way to secure APIs by requiring clients to pass a unique key with each request.

## How API Key Authentication Works

- **Client** includes an API key in the request (usually in a header).
- **Server** checks if the key is valid (e.g., exists in DB or config).
- If valid, allow the request; otherwise, return `401 Unauthorized`.

## API Key Example in C# (ASP.NET Web API / MVC)

### 1. Add API Key to Configuration

You can store it in `web.config`, `appsettings.json`, or hardcoded (not recommended):

```plaintext
// appsettings.json (.NET Core)
{
  "ApiKey": "your-secure-api-key-123"
}
```

### 2. Send API Key from Client

Send the API key in a request header:

```plaintext
GET /api/data
x-api-key: your-secure-api-key-123
```

### 3. Validate API Key in Middleware or Action Filter

#### Option A: Use Action Filter (`.NET Framework` or `.NET Core`)

```cs
public class ApiKeyAuthAttribute : Attribute, IAuthorizationFilter
{
    private const string ApiKeyHeader = "x-api-key";
    private const string ApiKey = "your-secure-api-key-123"; // Ideally from config

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeader, out var extractedApiKey))
        {
            context.Result = new UnauthorizedResult();
            return;
        }

        if (!ApiKey.Equals(extractedApiKey))
        {
            context.Result = new UnauthorizedResult();
        }
    }
}
```

Apply it to controller or method:

```cs
[ApiKeyAuth]
[Route("api/data")]
[HttpGet]
public IActionResult GetData()
{
    return Ok(new { message = "API Key validated!" });
}
```

### Option B: Middleware Approach (.NET Core)

For centralized API key handling:

```cs
public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string ApiKeyHeader = "x-api-key";
    private readonly string _configuredKey;

    public ApiKeyMiddleware(RequestDelegate next, IConfiguration config)
    {
        _next = next;
        _configuredKey = config["ApiKey"];
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(ApiKeyHeader, out var apiKey) ||
            _configuredKey != apiKey)
        {
            context.Response.StatusCode = 401; // Unauthorized
            await context.Response.WriteAsync("Unauthorized");
            return;
        }

        await _next(context);
    }
}
```

Register in `Startup.cs`:

```cs
app.UseMiddleware<ApiKeyMiddleware>();
```

## Best Practices for API Key Authentication

| Practice | Why it matters |
| --- | --- |
| Use HTTPS | Prevent key sniffing |
| Rotate keys periodically | Reduce risk in case of leak |
| Associate keys with clients/users | Helps track usage |
| Limit scope/rate by API key | Protect sensitive endpoints |
| Store keys securely | Avoid hardcoding sensitive info |

## Answers

### Answer by ICSM Computer

API Key authentication is a **simple, stateless** way to secure APIs by requiring clients to pass a unique key with each request.

## How API Key Authentication Works

- **Client** includes an API key in the request (usually in a header).
- **Server** checks if the key is valid (e.g., exists in DB or config).
- If valid, allow the request; otherwise, return `401 Unauthorized`.

## API Key Example in C# (ASP.NET Web API / MVC)

### 1. Add API Key to Configuration

You can store it in `web.config`, `appsettings.json`, or hardcoded (not recommended):

```plaintext
// appsettings.json (.NET Core)
{
  "ApiKey": "your-secure-api-key-123"
}
```

### 2. Send API Key from Client

Send the API key in a request header:

```plaintext
GET /api/data
x-api-key: your-secure-api-key-123
```

### 3. Validate API Key in Middleware or Action Filter

#### Option A: Use Action Filter (`.NET Framework` or `.NET Core`)

```cs
public class ApiKeyAuthAttribute : Attribute, IAuthorizationFilter
{
    private const string ApiKeyHeader = "x-api-key";
    private const string ApiKey = "your-secure-api-key-123"; // Ideally from config

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeader, out var extractedApiKey))
        {
            context.Result = new UnauthorizedResult();
            return;
        }

        if (!ApiKey.Equals(extractedApiKey))
        {
            context.Result = new UnauthorizedResult();
        }
    }
}
```

Apply it to controller or method:

```cs
[ApiKeyAuth]
[Route("api/data")]
[HttpGet]
public IActionResult GetData()
{
    return Ok(new { message = "API Key validated!" });
}
```

### Option B: Middleware Approach (.NET Core)

For centralized API key handling:

```cs
public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string ApiKeyHeader = "x-api-key";
    private readonly string _configuredKey;

    public ApiKeyMiddleware(RequestDelegate next, IConfiguration config)
    {
        _next = next;
        _configuredKey = config["ApiKey"];
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(ApiKeyHeader, out var apiKey) ||
            _configuredKey != apiKey)
        {
            context.Response.StatusCode = 401; // Unauthorized
            await context.Response.WriteAsync("Unauthorized");
            return;
        }

        await _next(context);
    }
}
```

Register in `Startup.cs`:

```cs
app.UseMiddleware<ApiKeyMiddleware>();
```

## Best Practices for API Key Authentication

| Practice | Why it matters |
| --- | --- |
| Use HTTPS | Prevent key sniffing |
| Rotate keys periodically | Reduce risk in case of leak |
| Associate keys with clients/users | Helps track usage |
| Limit scope/rate by API key | Protect sensitive endpoints |
| Store keys securely | Avoid hardcoding sensitive info |


---

Original Source: https://www.mindstick.com/interview/34213/how-do-you-implement-api-key-authentication

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
