# AlastackHmacAuth **Repository Path**: kyzala/AlastackHmacAuth ## Basic Information - **Project Name**: AlastackHmacAuth - **Description**: A .NET API supports Hmac and Hawk authentication. - **Primary Language**: C# - **License**: MIT - **Default Branch**: main - **Homepage**: https://github.com/kyzala/AlastackHmacAuth - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-02-25 - **Last Updated**: 2026-11-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: Alastack, Authentication, auth, HMAC, Hawk ## README # Alastack.HmacAuth Hmac and [Hawk](https://github.com/mozilla/hawk) authentication for .NET. Clients sign every request with a shared key; servers verify identity, request integrity (method, path, query, host, payload) and replay protection (timestamp + nonce). - **Alastack.HmacAuth** — client `DelegatingHandler`s: `HmacDelegatingHandler`, `HawkDelegatingHandler`. - **Alastack.HmacAuth.AspNetCore** — server `AuthenticationHandler`s, Hawk middleware and replay protection. - **Alastack.HmacAuth.Sql** — `ICredentialProvider` backed by any ADO.NET database. - **Alastack.HmacAuth.MongoDB** — `ICredentialProvider` backed by MongoDB. - **Alastack.HmacAuth.LiteDB** — `ICredentialProvider` backed by LiteDB. - **Alastack.HmacAuth.EFCore** — `ICredentialProvider` backed by Entity Framework Core. Targets .NET 8, .NET 10 and .NET 11. ```powershell dotnet add package Alastack.HmacAuth # client dotnet add package Alastack.HmacAuth.AspNetCore # server ``` ## Client ```csharp using Alastack.HmacAuth; var client = new HttpClient(new HmacDelegatingHandler("appId", "appSecret")) { BaseAddress = new Uri("https://api.example.com/") }; var hawkClient = new HttpClient(new HawkDelegatingHandler("authId", "authKey")); ``` With `IHttpClientFactory`: ```csharp services.AddHttpClient("api", c => c.BaseAddress = new Uri("https://api.example.com/")) .AddHttpMessageHandler(_ => new HmacDelegatingHandler("appId", "appSecret")); ``` Hawk can also verify the server response when the server enables server authorization: ```csharp var handler = new HawkDelegatingHandler(new HawkSettings { AuthId = "authId", AuthKey = "authKey", ValidateServerAuthorization = true, // verify Server-Authorization ValidateServerTime = true // verify tsm, then adjust TimeOffsetSeconds }); ``` The Hmac `Authorization` header is `Hmac {appId}:{timestamp}:{nonce}:{signature}:{payloadHash}`. Both handlers accept a settings object (`HmacSettings` / `HawkSettings`); the important ones are the id/key pair, `HashAlgorithm` (default `SHA256`, must match the server), `IncludePayloadHash` (default `true`) and `TimeOffsetSeconds` for a skewed clock. ## Server ```csharp builder.Services.AddAuthentication() .AddHmac(options => { options.CredentialProvider = new MemoryCredentialProvider( new Dictionary { ["appId1"] = new HmacCredential { AppId = "appId1", AppSecret = "appSecret1" } }); }) .AddHawk(options => { options.CredentialProvider = new MemoryCredentialProvider( new Dictionary { ["authId1"] = new HawkCredential { AuthId = "authId1", AuthKey = "authKey1" } }); }); var app = builder.Build(); app.UseAuthentication(); app.UseHawkServerAuthorization(); // only for Hawk response signing; after UseAuthentication app.UseAuthorization(); ``` Then protect endpoints with the scheme: `[Authorize(AuthenticationSchemes = "Hmac")]` (or `"Hawk"`). Replay protection is on by default: a nonce is remembered for `MaxReplayRequestAge` (60 s) and clock skew is limited to `TimeSkew` (300 s). `CredentialCacheTime` (300 s, `0` disables caching) controls credential caching, `TimeOffsetMilliseconds` corrects the server clock, and `EnableChallenge` (`false` by default) emits a `WWW-Authenticate` header on failure. ## Credential stores Assign any `ICredentialProvider` to `HmacOptions.CredentialProvider` / `HawkOptions.CredentialProvider`. SQL works with any `IDbConnection`, and the query must return the credential columns: ```csharp options.CredentialProvider = new SqlCredentialProvider( connectionString, "SELECT AppId, AppSecret, HmacAlgorithm, HashAlgorithm FROM HmacCredentials WHERE AppId = @Id"); ``` ```csharp // MongoDB: connection string, database, collection, id field options.CredentialProvider = new MongoDBCredentialProvider( "mongodb://localhost:27017", "credentialdb", "hmac", "appId"); // LiteDB: file connection string, collection, id field options.CredentialProvider = new LiteDBCredentialProvider( "Filename=Data\\hmac.db;Password=1234", "hmac", "appId"); // EF Core: reuse your DbContext options, then the table and key column var builder = new DbContextOptionsBuilder>(); builder.UseSqlServer(connectionString); options.CredentialProvider = new EFCoreCredentialProvider(builder, "HmacCredentials", "AppId"); ``` The storage-specific providers also expose helpers such as `InitDatabase()` and `AddCredential()` for seeding. ## Behind a reverse proxy The host and port are part of the signature. `DefaultHostResolver` reads the **leftmost** `X-Forwarded-Host` entry, so the original client host is used even through multiple proxies; if other code needs `Request.Host`/`Request.Scheme`, register the middleware and trust only your proxies: ```csharp app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedHost | ForwardedHeaders.XForwardedProto, ForwardLimit = 5, KnownProxies = { IPAddress.Parse("192.168.1.102"), IPAddress.Parse("192.168.1.103") } }); ``` Use `KnownIPNetworks` with `System.Net.IPNetwork` to trust a subnet (`KnownNetworks` is obsolete since .NET 8). Never trust arbitrary proxies while the app is reachable directly — a forged `X-Forwarded-Host` would change `Request.Host`. ## Samples Runnable examples for clients, servers, every credential store and a YARP proxy topology: https://github.com/kyzala/AlastackHmacAuth/tree/main/samples