How To Implement API Key Authentication In ASP.NET Core (2024)

In this week's newsletter I want to show you how to implement API Key authenticationin ASP.NET Core. This authentication approach uses an API Key to authenticate theclient of an API. You can pass the API Key to the API in a few ways, such as throughthe query string or a request header.

I will show you how to implement API Key authentication where the API key is passedin a request header. But the implementation would be similar if we were to use anyother approach.

When would you want to use API Key authentication? This kind of authenticationmechanism is common in Server-to-Server (S2S) communication. When your API servesrequest for other server-side applications to consume and integrate with. It'sless common in client-server communication scenarios.

Let's see how we can implement API Key authentication in ASP.NET Core!

Implementing API Key Authentication

We will start off by creating an attribute that we can place on endpointswhere we want to apply API Key authentication. It won't be any kind ofattribute, because we will use a ServiceFilterAttribute.

What a ServiceFilterAttribute allows us to do is specify a type for thefilter that will be created for that attribute.This means we can implement our authentication logic in an IAuthorizationFilter.With a ServiceFilterAttribute we also have support for dependency injectionin our IAuthorizationFilter implementation.

Let's first define the ApiKeyAttribute class:

public class ApiKeyAttribute : ServiceFilterAttribute{ public ApiKeyAttribute() : base(typeof(ApiKeyAuthorizationFilter)) { }}

In the ApiKeyAttribute we specify ApiKeyAuthorizationFilter class as thefilter that will be resolved from the DI container. Here's what it looks like:

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) { string apiKey = context.HttpContext.Request.Headers[ApiKeyHeaderName]; if (!_apiKeyValidator.IsValid(apiKey)) { context.Result = new UnauthorizedResult(); } }}

The implementation comes down to validating the API Key obtained fromthe header of the current request. If we determine that the API Keyis not valid, we set the value of AuthorizationFilterContext.Resultto a new instance of an UnauthorizedResult.

And lastly, all that's left for us to do is implement our customvalidation logic for the API Key inside of ApiKeyValidator:

public class ApiKeyValidator : IApiKeyValidator{ public bool IsValid(string apiKey) { // Implement logic for validating the API key. }}public interface IApiKeyValidator{ bool IsValid(string apiKey);}

The actual implementation for validating the API Key will vary basedon your use case, and where you are storing the API keys.For example, if you store the API keys in the database you would checkif the provided API Key exists in the database.If it exists, then validation passes.If it doesn't exist, then validation fails and we return anUnauthorizedResult.

Registering Services With Dependency Injection

We have to make sure to register our ApiKeyAuthorizationFilter andApiKeyValidator services with the dependency injection container.

builder.Services.AddSingleton<ApiKeyAuthorizationFilter>();builder.Services.AddSingleton<IApiKeyValidator, ApiKeyValidator>();

This will register them as singleton services in our application.You can use a different service scope such as Transient or Scopedif you need to.

Applying API Key Authentication To Endpoints

Finally, with our API Key authentication in place, we can apply theApiKeyAttribute attribute to our endpoints:

public class NewslettersController : ControllerBase{ [ApiKey] [HttpGet] public IActionResult Get() { // ... }}

In this case I'm applying the ApiKeyAttribute to an endpoint, butyou can also apply it on the NewslettersController and it will addauthentication to all the endpoints for that controller.

Next Steps

Now that you know how to implement API Key authentication, I think youshould also learn how to implement JWT authentication. And while you'reat it, why not throw authorization into the mix.

I made a few videos about JWT authentication and permission authorizationthat you should take a look at next:

How To Implement API Key Authentication In ASP.NET Core (2024)
Top Articles
Short Squeezes Explained | SoFi
Travel the U.S. for $30 A Day: The Ultimate Budget USA Road Trip
Is Sam's Club Plus worth it? What to know about the premium warehouse membership before you sign up
Chicago Neighborhoods: Lincoln Square & Ravenswood - Chicago Moms
From Algeria to Uzbekistan-These Are the Top Baby Names Around the World
Overnight Cleaner Jobs
Retro Ride Teardrop
Noaa Swell Forecast
Gameplay Clarkston
Morgan Wallen Pnc Park Seating Chart
Large storage units
Hallelu-JaH - Psalm 119 - inleiding
Ree Marie Centerfold
Scenes from Paradise: Where to Visit Filming Locations Around the World - Paradise
Bitlife Tyrone's
Daily Voice Tarrytown
Craigslist Maui Garage Sale
How your diet could help combat climate change in 2019 | CNN
Azur Lane High Efficiency Combat Logistics Plan
Craigslist Apartments Baltimore
[PDF] PDF - Education Update - Free Download PDF
Craigslist Roseburg Oregon Free Stuff
Bolly2Tolly Maari 2
Delta Math Login With Google
Alternatieven - Acteamo - WebCatalog
49S Results Coral
The Bold and the Beautiful
Frequently Asked Questions - Hy-Vee PERKS
Fbsm Greenville Sc
Petsmart Northridge Photos
Scottsboro Daily Sentinel Obituaries
3400 Grams In Pounds
Henry County Illuminate
Red Dead Redemption 2 Legendary Fish Locations Guide (“A Fisher of Fish”)
Craigslist en Santa Cruz, California: Tu Guía Definitiva para Comprar, Vender e Intercambiar - First Republic Craigslist
Mississippi weather man flees studio during tornado - video
ESA Science & Technology - The remarkable Red Rectangle: A stairway to heaven? [heic0408]
Free Crossword Puzzles | BestCrosswords.com
Levi Ackerman Tattoo Ideas
Oklahoma City Farm & Garden Craigslist
The Machine 2023 Showtimes Near Roxy Lebanon
Craigslist Sarasota Free Stuff
Electric Toothbrush Feature Crossword
Skyward Login Wylie Isd
David Turner Evangelist Net Worth
Estes4Me Payroll
How to Get a Check Stub From Money Network
Provincial Freeman (Toronto and Chatham, ON: Mary Ann Shadd Cary (October 9, 1823 – June 5, 1893)), November 3, 1855, p. 1
Coldestuknow
Vt Craiglist
Affidea ExpressCare - Affidea Ireland
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 6213

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.