AspNetCore.Authentication.ApiKey 3.1.1

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 either in Header, QueryParams or HeaderOrQueryParams.

Install-Package AspNetCore.Authentication.ApiKey -Version 3.1.1
dotnet add package AspNetCore.Authentication.ApiKey --version 3.1.1
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="3.1.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AspNetCore.Authentication.ApiKey --version 3.1.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Click here to open Github

Startup.cs (ASP.NET Core 3.0 or newer)
using AspNetCore.Authentication.ApiKey;
public class Startup
{
	public void ConfigureServices(IServiceCollection services)
	{
		// Add the ApiKey scheme authentication here..
		// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
		// If an implementation of IApiKeyProvider interface is registered in the dependency register as well as OnValidateKey delegete on options.Events is also set then this delegate will be used instead of an implementation of IApiKeyProvider.
		services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)

			// The below AddApiKeyInHeaderOrQueryParams without type parameter will require OnValidateKey delegete on options.Events to be set unless an implementation of IApiKeyProvider interface is registered in the dependency register.
			// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.*
			//.AddApiKeyInHeaderOrQueryParams(options =>

			// The below AddApiKeyInHeaderOrQueryParams with type parameter will add the ApiKeyProvider to the dependency register. 
			// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.
			.AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options =>
			{
				options.Realm = "Sample Web API";
				options.KeyName = "X-API-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 void ConfigureServices(IServiceCollection services)
	{
		// Add the ApiKey scheme authentication here..
		// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
		// If an implementation of IApiKeyProvider interface is registered in the dependency register as well as OnValidateKey delegete on options.Events is also set then this delegate will be used instead of an implementation of IApiKeyProvider.
		services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)

			// The below AddApiKeyInHeaderOrQueryParams without type parameter will require OnValidateKey delegete on options.Events to be set unless an implementation of IApiKeyProvider interface is registered in the dependency register.
			// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.*
			//.AddApiKeyInHeaderOrQueryParams(options =>

			// The below AddApiKeyInHeaderOrQueryParams with type parameter will add the ApiKeyProvider to the dependency register. 
			// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.
			.AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options =>
			{
				options.Realm = "Sample Web API";
				options.KeyName = "X-API-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 ApiKeyProvider(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; }
}

Configuration (ApiKeyOptions)

KeyName

Required to be set. It is the name of the header if it is setup as in-header or the name of the query parameter if set as in-query-string.

Realm

Required to be set if SuppressWWWAuthenticateHeader is not set to true. It is used with WWW-Authenticate response header when challenging un-authenticated requests.

ForLegacyIgnoreExtraValidatedApiKeyCheck

Default value is false.
If set to true, IApiKey.Key property returned from IApiKeyProvider.ProvideAsync(string) method is not compared with the key parsed from the request.
This extra check did not existed in the previous version. So you if want to revert back to old version validation, please set this to true.

SuppressWWWAuthenticateHeader

Default value is false.
When set to true, it will NOT return WWW-Authenticate response header when challenging un-authenticated requests.
When set to false, it will return WWW-Authenticate response header when challenging un-authenticated requests.

Events

The object provided by the application to process events raised by the api key authentication middleware.
The application may implement the interface fully, or it may create an instance of ApiKeyEvents and assign delegates only to the events it wants to process.

  • OnValidateKey
  • OnAuthenticationSucceeded
  • OnAuthenticationFailed
  • OnHandleChallenge
  • OnHandleForbidden

More details available on Github Click here to open Github

Click here to open Github

Startup.cs (ASP.NET Core 3.0 or newer)
using AspNetCore.Authentication.ApiKey;
public class Startup
{
	public void ConfigureServices(IServiceCollection services)
	{
		// Add the ApiKey scheme authentication here..
		// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
		// If an implementation of IApiKeyProvider interface is registered in the dependency register as well as OnValidateKey delegete on options.Events is also set then this delegate will be used instead of an implementation of IApiKeyProvider.
		services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)

			// The below AddApiKeyInHeaderOrQueryParams without type parameter will require OnValidateKey delegete on options.Events to be set unless an implementation of IApiKeyProvider interface is registered in the dependency register.
			// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.*
			//.AddApiKeyInHeaderOrQueryParams(options =>

			// The below AddApiKeyInHeaderOrQueryParams with type parameter will add the ApiKeyProvider to the dependency register. 
			// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.
			.AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options =>
			{
				options.Realm = "Sample Web API";
				options.KeyName = "X-API-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 void ConfigureServices(IServiceCollection services)
	{
		// Add the ApiKey scheme authentication here..
		// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
		// If an implementation of IApiKeyProvider interface is registered in the dependency register as well as OnValidateKey delegete on options.Events is also set then this delegate will be used instead of an implementation of IApiKeyProvider.
		services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)

			// The below AddApiKeyInHeaderOrQueryParams without type parameter will require OnValidateKey delegete on options.Events to be set unless an implementation of IApiKeyProvider interface is registered in the dependency register.
			// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.*
			//.AddApiKeyInHeaderOrQueryParams(options =>

			// The below AddApiKeyInHeaderOrQueryParams with type parameter will add the ApiKeyProvider to the dependency register. 
			// Please note if OnValidateKey delegete on options.Events is also set then this delegate will be used instead of ApiKeyProvider.
			.AddApiKeyInHeaderOrQueryParams<ApiKeyProvider>(options =>
			{
				options.Realm = "Sample Web API";
				options.KeyName = "X-API-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 ApiKeyProvider(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; }
}

Configuration (ApiKeyOptions)

KeyName

Required to be set. It is the name of the header if it is setup as in-header or the name of the query parameter if set as in-query-string.

Realm

Required to be set if SuppressWWWAuthenticateHeader is not set to true. It is used with WWW-Authenticate response header when challenging un-authenticated requests.

ForLegacyIgnoreExtraValidatedApiKeyCheck

Default value is false.
If set to true, IApiKey.Key property returned from IApiKeyProvider.ProvideAsync(string) method is not compared with the key parsed from the request.
This extra check did not existed in the previous version. So you if want to revert back to old version validation, please set this to true.

SuppressWWWAuthenticateHeader

Default value is false.
When set to true, it will NOT return WWW-Authenticate response header when challenging un-authenticated requests.
When set to false, it will return WWW-Authenticate response header when challenging un-authenticated requests.

Events

The object provided by the application to process events raised by the api key authentication middleware.
The application may implement the interface fully, or it may create an instance of ApiKeyEvents and assign delegates only to the events it wants to process.

  • OnValidateKey
  • OnAuthenticationSucceeded
  • OnAuthenticationFailed
  • OnHandleChallenge
  • OnHandleForbidden

More details available on Github Click here to open Github

Release Notes

- Ability to have ApiKey in Authorization header added
- Fixed extensions methods to use correct handler
- Fixed issue with resolving of IApiKeyProvider implementation when using multiple schemes

NuGet packages (1)

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

Package Downloads
Een.Common
Nuget package for common helpers and enums

GitHub repositories

This package is not used by any popular GitHub repositories.

Version History

Version Downloads Last updated
3.1.1 970 10/31/2020
3.1.0 406 10/20/2020
2.2.0 16,397 12/16/2019