AspNetCore.Authentication.ApiKey 2.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package AspNetCore.Authentication.ApiKey --version 2.2.0                
NuGet\Install-Package AspNetCore.Authentication.ApiKey -Version 2.2.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="2.2.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AspNetCore.Authentication.ApiKey --version 2.2.0                
#r "nuget: AspNetCore.Authentication.ApiKey, 2.2.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install AspNetCore.Authentication.ApiKey as a Cake Addin
#addin nuget:?package=AspNetCore.Authentication.ApiKey&version=2.2.0

// Install AspNetCore.Authentication.ApiKey as a Cake Tool
#tool nuget:?package=AspNetCore.Authentication.ApiKey&version=2.2.0                

AspNetCore.Authentication.ApiKey

Easy to use and very light weight Microsoft style API Key Authentication Implementation for ASP.NET Core. It can be setup so that it can accept API Key in Header, QueryParams or HeaderOrQueryParams.

View On GitHub

Example Usage

Setting it up is quite simple. You will need basic working knowledge of ASP.NET Core 2.2 or newer to get started using this code.

On Startup.cs, as shown below, add 2 lines in ConfigureServices method services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme).AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options => { options.Realm = "My App"; options.KeyName = "X-API-KEY"; });. And a line app.UseAuthentication(); in Configure method.

Also add an implementation of IApiKeyProvider as shown below in ApiKeyProvider.cs and also an implementation of IApiKey as shown below in ApiKey.cs.

NOTE: Always use HTTPS (SSL Certificate) protocol in production when using API Key authentication.

Startup.cs (ASP.NET Core 3.0 or newer)
using AspNetCore.Authentication.ApiKey;
public class Startup
{
	public Startup(IConfiguration configuration)
	{
		Configuration = configuration;
	}

	public IConfiguration Configuration { get; }

	public void ConfigureServices(IServiceCollection services)
	{
		// Add the API Key authentication here..
		// AddApiKeyInHeaderOrQueryParams extension takes an implementation of IApiKeyProvider for validating the key. 
		// It also requires Realm and KeyName to be set in the options.
		services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)
			//// use below to accept API Key either in header or query parameter
			.AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options => 
			{ 
				options.Realm = "My App"; 
				options.KeyName = "X-API-KEY";	// Your api key name which the clients will require to send the key.
			});

			//// use below instead to only accept API Key in header
			//.AddApiKeyInHeader<ApiKeyProvider>(options => 
			//{ 
			//	options.Realm = "My App"; 
			//	options.KeyName = "X-API-KEY";	// Your api key name which the clients will require to send the key.
			//});

			//// use below instead to only accept API Key in query parameter
			//.AddApiKeyQueryParams<ApiKeyProvider>(options => 
			//{ 
			//	options.Realm = "My App"; 
			//	options.KeyName = "X-API-KEY";	// Your api key name which the clients will require to send the key.
			//});

		services.AddControllers();

		//// By default, authentication is not challenged for every request which is ASP.NET Core's default intended behaviour.
		//// So to challenge authentication for every requests please use below option instead of above services.AddControllers().
		//services.AddControllers(options => 
		//{
		//	options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
		//});
	}

	public void Configure(IApplicationBuilder app, IHostingEnvironment env)
	{
		app.UseHttpsRedirection();

		// The below order of pipeline chain is important!
		app.UseRouting();

		app.UseAuthentication();
		app.UseAuthorization();

		app.UseEndpoints(endpoints =>
		{
			endpoints.MapControllers();
		});
	}
}
Startup.cs (ASP.NET Core 2.2)
using AspNetCore.Authentication.ApiKey;
public class Startup
{
	public Startup(IConfiguration configuration)
	{
		Configuration = configuration;
	}

	public IConfiguration Configuration { get; }

	public void ConfigureServices(IServiceCollection services)
	{
		// Add the API Key authentication here..
		// AddApiKeyInHeaderOrQueryParams extension takes an implementation of IApiKeyProvider for validating the key. 
		// It also requires Realm and KeyName to be set in the options.
		services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)
			//// use below to accept API Key either in header or query parameter
			.AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options => 
			{ 
				options.Realm = "My App"; 
				options.KeyName = "X-API-KEY";	// Your api key name which the clients will require to send the key.
			});

			//// use below instead to only accept API Key in header
			//.AddApiKeyInHeader<ApiKeyProvider>(options => 
			//{ 
			//	options.Realm = "My App"; 
			//	options.KeyName = "X-API-KEY";	// Your api key name which the clients will require to send the key.
			//});

			//// use below instead to only accept API Key in query parameter
			//.AddApiKeyInQueryParams<ApiKeyProvider>(options => 
			//{ 
			//	options.Realm = "My App"; 
			//	options.KeyName = "X-API-KEY";	// Your api key name which the clients will require to send the key.
			//});

		services.AddMvc();

		//// By default, authentication is not challenged for every request which is ASP.NET Core's default intended behaviour.
		//// So to challenge authentication for every requests please use below option instead of above services.AddMvc().
		//services.AddMvc(options => 
		//{
		//	options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
		//});
	}

	public void Configure(IApplicationBuilder app, IHostingEnvironment env)
	{
		app.UseAuthentication();
		app.UseMvc();
	}
}
ApiKeyProvider.cs
using AspNetCore.Authentication.ApiKey;
public class ApiKeyProvider : IApiKeyProvider
{
	private readonly ILogger<ApiKeyProvider> _logger;
	
	public BasicUserValidationService(ILogger<ApiKeyProvider> logger)
	{
		_logger = logger;
	}

	public Task<IApiKey> ProvideAsync(string key)
	{
		try
		{
			// write your validation implementation here and return an instance of a valid ApiKey or retun null for an invalid key.
			return Task.FromResult(null);
		}
		catch (System.Exception exception)
		{
			_logger.LogError(exception, exception.Message);
			throw;
		}
	}
}
ApiKey.cs
using AspNetCore.Authentication.ApiKey;
class ApiKey : IApiKey
{
	public ApiKey(string key, string owner, List<Claim> claims = null)
	{
		Key = key;
		OwnerName = owner;
		Claims = claims ?? new List<Claim>();
	}

	public string Key { get; }
	public string OwnerName { get; }
	public IReadOnlyCollection<Claim> Claims { get; }
}

Additional Notes

Please note that, by default, with ASP.NET Core, all the requests are not challenged for authentication. So don't worry if your ApiKeyProvider is not hit when you don't pass the required api key authentication details with the request. It is a normal behaviour. ASP.NET Core challenges authentication only when it is specifically told to do so either by decorating controller/method with [Authorize] filter attribute or by some other means.

However, if you want all the requests to challenge authentication by default, depending on what you are using, you can add the below options line to ConfigureServices method on Startup class.

services.AddControllers(options => 
{ 
    options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
});

// OR

services.AddMvc(options => 
{
    options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
});

If you are not using MVC but, using Endpoints on ASP.NET Core 3.0 or newer, you can add a chain method .RequireAuthorization() to the endpoint map under Configure method on Startup class as shown below.

app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/", async context =>
    {
        await context.Response.WriteAsync("Hello World!");
    }).RequireAuthorization();  // NOTE THIS HERE!!!! 
});

License

MIT License

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (21)

Showing the top 5 NuGet packages that depend on AspNetCore.Authentication.ApiKey:

Package Downloads
Een.Common

Nuget package for common helpers and enums

Elsa.Identity

Provides a default identity solution.

Elsa.EntityFrameworkCore

Provides Entity Framework Core implementations of various abstractions from various modules.

OLT.AspNetCore.Authentication.ApiKey

OLT AspNetCore Autentication for API Key in the Header or Query

Elsa.EntityFrameworkCore.SqlServer

Provides SQL Server EF Core migrations for various modules.

GitHub repositories (4)

Showing the top 4 popular GitHub repositories that depend on AspNetCore.Authentication.ApiKey:

Repository Stars
elsa-workflows/elsa-core
A .NET workflows library
simpleidserver/SimpleIdServer
OpenID, OAuth 2.0, SCIM2.0, UMA2.0, FAPI, CIBA & OPENBANKING Framework for ASP.NET Core
mihirdilip/aspnetcore-authentication-apikey
Easy to use and very light weight Microsoft style API Key Authentication Implementation for ASP.NET Core. It can be setup so that it can accept API Key in Header, Authorization Header, QueryParams or HeaderOrQueryParams.
microsoft/project-oagents
Experimental AI Agents Framework
Version Downloads Last updated
8.0.1 588,265 1/29/2024
8.0.0 220,240 11/22/2023
7.0.0 865,490 11/22/2022
6.0.1 993,109 1/7/2022
5.1.0 645,021 2/26/2021
5.0.0 80,176 12/7/2020
3.1.1 145,435 10/31/2020
3.1.0 3,385 10/20/2020
2.2.0 231,845 12/16/2019