Securing ASP.NET Web APIs with API Keys and Role-Based Authentication admin March 17, 2025

Securing ASP.NET Web APIs with API Keys and Role-Based Authentication

Security is a crucial aspect of any ASP.NET Core Web API. In this guide, I will cover how to:

Secure an API using API Keys (custom auth model)
Implement Role-Based Authentication with JWT Tokens

Why Secure Your API?

APIs are often exposed to the internet, making them vulnerable to unauthorized access. By securing them with API Keys and Role-Based Authentication, we can:

. Restrict access to authorized clients
. Control user permissions based on their roles
. Protect sensitive data

Part 1: Securing API with API Keys

What is an API Key?

An API Key is a unique identifier used to authenticate requests from clients. Unlike JWT tokens, API keys are static and usually provided as a header or query parameter.

Implementing API Key Authentication in ASP.NET Core

Step 1: Create a Middleware for API Key Validation

Create a middleware to check for a valid API key. For this lets create a new class ApiKeyMiddleware.cs

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string API_KEY_HEADER = "X-API-KEY";
    private readonly string _apiKey;

    public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
    {
        _next = next;
        _apiKey = configuration["ApiKey"];  // Load API key from appsettings.json
    }

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(API_KEY_HEADER, out var extractedApiKey) || extractedApiKey != _apiKey)
        {
            context.Response.StatusCode = 401; // Unauthorized
            await context.Response.WriteAsync("Unauthorized: Invalid API Key");
            return;
        }

        await _next(context); // Continue request pipeline if key is valid
    }
}

Step 2: Register the Middleware in Program.cs

Modify your Program.cs to use the middleware.



app.UseMiddleware();

Step 3: Store the API Key Securely in appsettings.json

{
  "ApiKey": "MySuperSecretAPIKey"
}

Step 4: Send API Key in Requests

Your API now requires the API key in the header. If the key is missing or invalid, the API will return 401 Unauthorized.

Part 2: Implement Role-Based Authentication with JWT

Now, let’s implement JWT Authentication and Role-Based Access Control (RBAC).

Before that if you are interested, please read my blog here about the JWT

2.1 Install Required Packages

Run the following NuGet commands:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.AspNetCore.Identity
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

2.2 Configure Authentication in Program.cs

Modify your Program.cs file to enable JWT authentication.

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

var key = Encoding.ASCII.GetBytes("Your_Secret_Key_Here"); // Replace with a secure key

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
2.3 Create JWT Token Generation Logic

Now you may generate JWT logic as mentioned in in my previous blog

2.4 Secure Endpoints with Role-Based Authorization

You can now restrict API access based on roles.

[Authorize(Roles = "Admin")]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
return Ok("This is a protected API endpoint for Admins only.");
}

That’s it!

Send the token in the Authorization header for protected APIs:

Conclusion

API Key Authentication is useful for machine-to-machine communication.
JWT Authentication with Role-Based Access Control (RBAC) ensures user-level security.
Combining both methods enhances API security and prevents unauthorized access.

Write a comment
Your email address will not be published. Required fields are marked *
Scroll
📞Request Call Back