Skip to content

API Key Authentication Provider & Client Library for ASP.NET Core Web APIs

License

Notifications You must be signed in to change notification settings

justified777/aspnetcore-apikeys

 
 

Repository files navigation

Introduction

A server-side and client-side library for API key authentication with ASP.NET core.

Build status

Packages

Package NuGet Stable NuGet Pre-release MyGet Dev
Csg.AspNetCore.Authentication.ApiKey n/a n/a Link
Csg.ApiKeyGenerator n/a n/a Link

Getting Started

  1. Install nuget package
  2. Configure API for Authentication
  3. Enjoy!

API Configuration

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

Example Client Usage

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 and Test

  1. build.ps1 / build.cmd should build and run all tests

About

API Key Authentication Provider & Client Library for ASP.NET Core Web APIs

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 90.8%
  • PowerShell 8.7%
  • Batchfile 0.5%