A server-side and client-side library for API key authentication with ASP.NET core.
Package | NuGet Stable | NuGet Pre-release | MyGet Dev |
---|---|---|---|
Csg.AspNetCore.Authentication.ApiKey | n/a | n/a | Link |
Csg.ApiKeyGenerator | n/a | n/a | Link |
- Install nuget package
- Configure API for Authentication
- Enjoy!
See the full example API project with a working Open API (Swagger) definition as well.
appsettings.json example
{
"ApiKeys": {
"Client1": "secret1234"
}
}
Startup.cs example
public void ConfigureServices(IServiceCollection services)
{
services.Configure<Csg.AspNetCore.Authentication.ApiKey.ConfigurationApiKeyStoreOptions>("ApiKeys", this.Configuration);
services.AddConfigurationApiKeyStore();
services.AddAuthentication(Csg.AspNetCore.Authentication.ApiKey.ApiKeyDefaults.Name).AddApiKey();
services.AddMvc();
}
Remember to require authentication on your controller, or require auth for all requests
[Authorize]
public class EchoController : Controller
See the full example API project with working calls to the Example API.
static void Main(string[] args)
{
string clientID = "Client1";
string secret = "secret1234";
var client = new System.Net.Http.HttpClient();
Console.WriteLine("Calling an API using a static API key");
client.AddApiKeyAuthorizationHeader(clientID, secret);
var response = client.GetAsync("http://localhost:5001/api/echo/HelloWorld").ConfigureAwait(false).GetAwaiter().GetResult();
Console.WriteLine($"Response Code: {response.StatusCode}");
var content = response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
Console.WriteLine($"Response Content: {content}");
Console.WriteLine("Calling an API using a time-based token generated from the API key");
client.AddApiKeyAuthorizationHeader(clientID, secret, DateTimeOffset.UtcNow);
response = client.GetAsync("http://localhost:5001/api/echo/HelloWorld").ConfigureAwait(false).GetAwaiter().GetResult();
Console.WriteLine($"Response Code: {response.StatusCode}");
content = response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
Console.WriteLine($"Response Content: {content}");
Console.WriteLine("Press any key to end...");
Console.ReadKey();
}
- build.ps1 / build.cmd should build and run all tests