AspNetCore.Authentication.ApiKey 5.1.0

Install-Package AspNetCore.Authentication.ApiKey -Version 5.1.0
dotnet add package AspNetCore.Authentication.ApiKey --version 5.1.0
<PackageReference Include="AspNetCore.Authentication.ApiKey" Version="5.1.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AspNetCore.Authentication.ApiKey --version 5.1.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: AspNetCore.Authentication.ApiKey, 5.1.0"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. 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=5.1.0

// Install AspNetCore.Authentication.ApiKey as a Cake Tool
#tool nuget:?package=AspNetCore.Authentication.ApiKey&version=5.1.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

View On GitHub

Example Usage

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

There are 2 different ways of using this library to do it's job. Both ways can be mixed if required.
1] Using the implementation of IApiKeyProvider
2] Using ApiKeyOptions.Events (OnValidateKey delegate) which is same approach you will find on Microsoft's authentication libraries

Notes:

  • It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
  • If an implementation of IApiKeyProvider interface is used as well as options.Events.OnValidateKey delegate is also set then this delegate will be used first.

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

Startup.cs (ASP.NET Core 3.0 onwards)
using AspNetCore.Authentication.ApiKey;
public class Startup
{
	public void ConfigureServices(IServiceCollection services)
	{
		// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
		// If an implementation of IApiKeyProvider interface is used as well as options.Events.OnValidateKey delegate is also set then this delegate will be used first.

		services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)

			// The below AddApiKeyInHeaderOrQueryParams without type parameter will require options.Events.OnValidateKey delegete to be set.
			//.AddApiKeyInHeaderOrQueryParams(options =>

			// The below AddApiKeyInHeaderOrQueryParams with type parameter will add the ApiKeyProvider to the dependency container. 
			.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 FallbackPolicy option.
		//services.AddAuthorization(options =>
		//{
		//	options.FallbackPolicy = 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.0 onwards)
using AspNetCore.Authentication.ApiKey;
public class Startup
{
	public void ConfigureServices(IServiceCollection services)
	{
		// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
		// If an implementation of IApiKeyProvider interface is used as well as options.Events.OnValidateKey delegate is also set then this delegate will be used first.

		services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme)

			// The below AddApiKeyInHeaderOrQueryParams without type parameter will require options.Events.OnValidateKey delegete to be set.
			//.AddApiKeyInHeaderOrQueryParams(options =>

			// The below AddApiKeyInHeaderOrQueryParams with type parameter will add the ApiKeyProvider to the dependency container. 
			.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<IApiKeyProvider> _logger;
	private readonly IApiKeyRepository _apiKeyRepository;
	
	public ApiKeyProvider(ILogger<IApiKeyProvider> logger, IApiKeyRepository apiKeyRepository)
	{
		_logger = logger;
		_apiKeyRepository = apiKeyRepository;
	}

	public async 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 await _apiKeyRepository.GetApiKeyAsync(key);
			return 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_params.

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.

SuppressWWWAuthenticateHeader

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

IgnoreAuthenticationIfAllowAnonymous (available on ASP.NET Core 3.0 onwards)

Default value is false.
If set to true, it checks if AllowAnonymous filter on controller action or metadata on the endpoint which, if found, it does not try to authenticate the request.

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.

ForLegacyUseKeyNameAsSchemeNameOnWWWAuthenticateHeader

Default value is false. If set to true, value of KeyName property is used as scheme name on the WWW-Authenticate response header when challenging un-authenticated requests. If set to false, the authentication scheme name (set when setting up authentication on authentication builder) is used as scheme name on the 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

NuGet packages (2)

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

Package Downloads
Een.Common

Nuget package for common helpers and enums

OLT.AspNetCore.Authentication.ApiKey

OLT AspNetCore Autentication for API Key in the Header or Query

GitHub repositories (1)

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

Repository Stars
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.
Version Downloads Last updated
5.1.0 112,408 2/26/2021
5.0.0 47,698 12/7/2020
3.1.1 20,642 10/31/2020
3.1.0 1,506 10/20/2020
2.2.0 63,299 12/16/2019

- WWW-Authenticate challenge header now returns SchemeName as scheme part instead of ApiKeyOptions.KeyName
- WWW-Authenticate challenge header now has 2 new parameters 'in' and 'key_name' in value part  
- ForLegacyUseKeyNameAsSchemeNameOnWWWAuthenticateHeader added to the ApiKeyOptions
- In Authorization Header now able to use either SchemeName or ApiKeyOptions.KeyName when matching AuthorizationHeader Scheme
- Visibility of all the handlers changed to public
- Tests added
- Readme updated
- Copyright year updated on License