HMAC Authentication Implementation for ASP.NET Core
Repo loresoft/HashGate, read from GitHub 1 min ago. loresoft has not joined Take My Repo.
loresoft/HashGate is a public repo on GitHub by loresoft. HMAC Authentication Implementation for ASP.NET Core. It declares the MIT license on GitHub. It is written mainly in C#, has 12 stars and last changed on 2026-11-11. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-22.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
A HMAC (Hash-based Message Authentication Code) authentication system for ASP.NET Core applications. This library provides both server-side authentication and client-side HTTP handlers for secure API communication.
| Package | Version | Description |
|---|---|---|
| HashGate.AspNetCore | Server-side HMAC authentication for ASP.NET Core applications | |
| HashGate.HttpClient | Client-side HTTP message handler for HMAC authentication |
This library implements HMAC authentication similar to AWS Signature Version 4 and Azure HMAC Authentication. All HTTP requests must be transmitted over TLS and include cryptographic signatures to ensure request integrity and authenticity.
HMAC authentication is particularly well-suited for server-to-server communication and microservices architectures for following reasons:
Install the NuGet packages for your server and client projects:
Using .NET CLI:
dotnet add package HashGate.AspNetCore
Using PowerShell:
Install-Package HashGate.AspNetCoreUsing .NET CLI:
dotnet add package HashGate.HttpClient
Using PowerShell:
Install-Package HashGate.HttpClientusing HashGate.AspNetCore; var builder = WebApplication.CreateBuilder(args); // Add HMAC authentication builder.Services .AddAuthentication() .AddHmacAuthentication(); builder.Services.AddAuthorization(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); // Your protected endpoints app.MapGet("/api/secure", () => "Hello, authenticated user!") .RequireAuthorization(); app.Run();
appsettings.json (Server):
{
"HmacSecrets": {
"MyClientId": "your-secret-key-here",
"AnotherClient": "another-secret-key"
}
}Production tip: Storing secrets in
appsettings.jsonis fine for local development and quick starts. For production, implement a Custom Key Provider to load secrets from a secure store such as Azure Key Vault, a database, or another secrets manager.
Use AddHmacClient to register an HttpClient whose outgoing requests are automatically signed with HMAC
authentication. It is the HMAC-enabled equivalent of AddHttpClient, and returns an IHttpClientBuilder
so you can chain additional configuration.
using HashGate.HttpClient; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var builder = Host.CreateApplicationBuilder(args); // Register a named HMAC client and set its base address builder.Services.AddHmacClient("SecureApi", (sp, client) => { client.BaseAddress = new Uri("https://api.example.com"); }); var app = builder.Build(); // Get the HttpClient and make authenticated requests var httpClientFactory = app.Services.GetRequiredService<IHttpClientFactory>(); var httpClient = httpClientFactory.CreateClient("SecureApi"); var response = await httpClient.GetAsync("/api/secure");
appsettings.json (Client):
{
"HmacAuthentication": {
"Client": "MyClientId",
"Secret": "your-secret-key-here",
"BaseAddress": "https://api.example.com/"
}
}For typed clients, base address resolution, and runtime provisioning, see Client Configuration.
Each client must have:
Every authenticated request must include these headers:
| Request Header | Description |
|---|---|
| Host | Internet host and port number |
| x-timestamp | Unix timestamp (seconds since epoch) when the request was created. Must be within 5 minutes of current server time |
| x-content-sha256 | Base64-encoded SHA256 hash of the request body. Required even for requests with empty bodies |
| x-nonce | Unique per-request value (GUID/UUID). Included by default in signed headers and auto-generated by the .NET client. Not server-enforced, but strongly recommended — without it, identical requests within the same second are rejected when replay protection is enabled (the default) |
| Authorization | HMAC authentication information (see format details below) |
GET /api/users?page=1 HTTP/1.1 Host: api.example.com x-timestamp: 1722776096 x-nonce: a3f1c2d4e5b64a7f8c9d0e1f2a3b4c5d x-content-sha256: 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU= Authorization: HMAC Client=123456789&SignedHeaders=host;x-timestamp;x-content-sha256;x-nonce&Signature=AbCdEf123456...
Authorization: HMAC Client=<value>&SignedHeaders=<value>&Signature=<value>
| Parameter | Description | Required |
|---|---|---|
| HMAC | Authorization scheme identifier | Yes |
| Client | The client identifier of the access key used to compute the signature | Yes |
| SignedHeaders | Semicolon-separated list of HTTP headers included in the signature | Yes |
| Signature | Base64-encoded HMACSHA256 hash of the String-To-Sign | Yes |
The unique identifier for the access key used to compute the signature. This allows the server to identify which HMAC secret key to use for signature verification.
Semicolon-separated list of HTTP header names that were included in the signature calculation. These headers must be present in the request with the exact values used during signing.
The following headers must always be included in SignedHeaders. The server enforces their presence and will reject requests that omit them:
hostx-timestamp — required for replay protection; cryptographically binds the timestamp to the signaturex-content-sha256 — required for body integrity; cryptographically binds the content hash to the signatureYou can include additional headers beyond the required set for enhanced security:
host;x-timestamp;x-content-sha256;x-nonce;content-type;accept
The signature is a Base64-encoded HMACSHA256 hash of the String-To-Sign using the client's secret key:
Signature = base64_encode(HMACSHA256(String-To-Sign, Secret))
The String-To-Sign is a canonical representation of the request constructed as follows:
String-To-Sign = HTTP_METHOD + '\n' + path_and_query + '\n' + signed_headers_values
| Component | Description |
|---|---|
| HTTP_METHOD | Uppercase HTTP method name (GET, POST, PUT, DELETE, etc.) |
| path_and_query | The request path and query string (e.g., /api/users?page=1) |
| signed_headers_values | Semicolon-separated list of header values in the same order as specified in SignedHeaders |
For a GET request to /kv?fields=*&api-version=1.0:
String-To-Sign = "GET" + '\n' + // HTTP method "/kv?fields=*&api-version=1.0" + '\n' + // path and query "api.example.com;1722776096;47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=;a3f1c2d4e5b64a7f8c9d0e1f2a3b4c5d" // header values
// Basic configuration with default settings builder.Services .AddAuthentication() .AddHmacAuthentication(); // Configuration with custom options builder.Services .AddAuthentication() .AddHmacAuthentication(options => { options.ToleranceWindow = 10; // 10 minutes timestamp tolerance options.SecretSectionName = "MyHmacSecrets"; // Custom config section });
HashGate provides two layers of replay protection:
Layer 1 — Timestamp window (always active): The server rejects any request whose x-timestamp falls outside ToleranceWindow minutes of server time (default: 5 minutes).
Layer 2 — Signature replay cache (enabled by default): EnableReplayProtection is true by default. The server records each validated signature and immediately rejects any duplicate that arrives within its validity window — even within the same second. To opt out, set EnableReplayProtection = false.
// Server — replay protection is enabled by default builder.Services .AddAuthentication() .AddHmacAuthentication(); // To disable replay protection: // .AddHmacAuthentication(options => options.EnableReplayProtection = false);
Important — nonce: The timestamp has only one-second resolution, so two identical requests sent within the same second produce the same signature and the second would be falsely rejected. Every request automatically includes a unique
x-nonceheader, making each signature cryptographically unique.
// Client — x-nonce is always included automatically services.AddHmacClient(configureOptions: options => { options.Client = "MyClientId"; options.Secret = "my-secret-key"; });
Multi-server / distributed deployments: The default DefaultHmacReplayProtection is backed by HybridCache (in-process L1). Register a distributed cache (e.g. Redis) alongside it; HybridCache will automatically promote it to the L2 backing store — no custom code required.
// Add Redis as the distributed backing store for replay protection builder.Services.AddStackExchangeRedisCache(options => options.Configuration = builder.Configuration.GetConnectionString("Redis")); builder.Services .AddAuthentication() .AddHmacAuthentication();
Use AddHmacClient to register an HttpClient whose outgoing requests are automatically signed with HMAC
authentication. It is the HMAC-enabled equivalent of AddHttpClient and returns an IHttpClientBuilder so you
can chain additional configuration. Options bind from the HmacAuthentication configuration section by default.
// Default (unnamed) client — binds options from the "HmacAuthentication" section services.AddHmacClient(); // Named client with base address and custom options services.AddHmacClient("SecureApi", configureClient: (sp, client) => client.BaseAddress = new Uri("https://api.example.com"), configureOptions: options => { options.Client = "MyClientId"; options.Secret = "my-secret-key"; options.SignedHeaders = ["host", "x-timestamp", "x-content-sha256", "x-nonce", "content-type"]; });
AddHmacClient always assigns a base address to the underlying HttpClient so that relative request URIs
(such as /api/secure) are accepted. The base address is resolved in the following order:
HmacAuthenticationOptions.BaseAddress — bound from the BaseAddress value in the
HmacAuthentication configuration section (or set via configureOptions). When present, it is used as the
client's base address.configureClient override — the configureClient delegate runs after the options-based base address is
applied, so setting client.BaseAddress there takes precedence. This is useful when the address is not part
of configuration.http://hashgate.invalid/) is assigned. HmacAuthenticationHttpHandler detects this placeholder at request
time and rewrites the request URI using the current BaseAddress from options. This supports scenarios where
the base address is provisioned after startup (see Runtime Provisioning).Because the handler resolves BaseAddress from the options monitor on every request, later updates applied
through OptionsUpdater<HmacAuthenticationOptions> are observed automatically — even for clients created before
the base address was provisioned.
Register a typed HttpClient whose outgoing requests are automatically signed with HMAC. Each typed client
gets its own named HmacAuthenticationOptions (keyed by the client type), so multiple clients can use
different credentials and base addresses.
// Binds options from the "HmacAuthentication" configuration section services.AddHmacClient<MyApiClient>(); // Or bind from a custom section and configure the HttpClient services.AddHmacClient<MyApiClient>("MyApi", (sp, http) => { http.Timeout = TimeSpan.FromSeconds(30); });
For clients that are provisioned after startup — for example when the base address, client id, and secret
are not known until they are loaded from an external source at runtime — register the client during
Program.cs, then apply the provisioned values once they are available by resolving
OptionsUpdater<HmacAuthenticationOptions>.
Updates are applied through the options monitor cache, so any typed client or message handler that resolves options after the update observes the new values — even if a request was already made with the initial configuration.
// Program.cs — no credentials required yet builder.Services.AddHmacClient<MyApiClient>();
// After startup — load the provisioned settings and apply them var provisioned = await LoadProvisionedSettingsAsync(); var updater = serviceProvider.GetRequiredService<OptionsUpdater<HmacAuthenticationOptions>>(); updater.Update<MyApiClient>(options => { options.BaseAddress = new Uri(provisioned.BaseAddress); options.Client = provisioned.Client; options.Secret = provisioned.Secret; }); // The next request through MyApiClient uses the provisioned credentials
The updater also exposes Update(Action<HmacAuthenticationOptions>) for the default options instance,
Update(string name, Action<HmacAuthenticationOptions>) for a named instance, and Reset overloads to
revert to the originally configured values.
HashGate.AspNetCore emits OpenTelemetry-compatible traces and metrics through System.Diagnostics.
| Signal | Name |
|---|---|
| Activity source | HashGate.AspNetCore |
| Meter | HashGate.AspNetCore |
Authentication activities are emitted as HashGate.Authenticate for requests that include an HMAC Authorization header. Requests without an authorization header, or requests using another authentication scheme such as Bearer, return no authentication result and do not emit a HashGate authentication activity.
using OpenTelemetry.Metrics; using OpenTelemetry.Trace; builder.Services.AddOpenTelemetry() .WithTracing(tracing => tracing .AddAspNetCoreInstrumentation() .AddSource("HashGate.AspNetCore")) .WithMetrics(metrics => metrics .AddAspNetCoreInstrumentation() .AddMeter("HashGate.AspNetCore"));
| Activity | Description |
|---|---|
HashGate.Authenticate |
HMAC authentication validation for a request |
Common activity tags:
| Tag | Description |
|---|---|
hashgate.auth.scheme |
Authentication scheme name |
hashgate.auth.result |
success or failure |
hashgate.auth.failure_reason |
Failure reason, such as invalid_signature, invalid_timestamp, invalid_content_hash, missing_required_signed_headers, too_many_signed_headers, replayed_signature, or authentication_error |
hashgate.client |
HMAC client identifier for grouping API usage by client |
hashgate.endpoint |
Endpoint display name or request path for grouping API usage by endpoint |
hashgate.replay_protection.enabled |
Whether replay protection is enabled for the scheme |
hashgate.replay_protection.result |
Replay protection outcome: new, replay, or not_configured |
hashgate.hmac.signed_headers.count |
Number of headers included in the signature |
hashgate.rate_limit.policy |
Resolved HashGate rate limit policy name |
hashgate.rate_limit.client |
Client or remote IP used for the rate limit partition |
hashgate.rate_limit.endpoint |
Endpoint key used for rate limiting |
hashgate.rate_limit.partition_source |
hmac_client or remote_ip |
hashgate.rate_limit.rejected |
true when the request was rejected by rate limiting |
hashgate.rate_limit.retry_after_ms |
Retry delay in milliseconds for rejected requests |
Authentication activities also add hashgate.content_hash.validated when the request body hash is valid and hashgate.content_hash.failed when body hash validation fails. Failed authentication activities are marked with ActivityStatusCode.Error.
| Metric | Type | Unit | Description |
|---|---|---|---|
hashgate.auth.requests |
Counter | {request} |
Number of HMAC authentication attempts |
hashgate.auth.failures |
Counter | {failure} |
Number of failed HMAC authentication attempts |
hashgate.auth.duration |
Histogram | ms |
Duration of HMAC authentication attempts |
hashgate.replay_protection.checks |
Counter | {check} |
Number of HMAC replay protection checks |
hashgate.replay_protection.replays |
Counter | {replay} |
Number of rejected replayed HMAC signatures |
hashgate.rate_limit.rejections |
Counter | {rejection} |
Number of requests rejected by HashGate rate limiting |
hashgate.rate_limit.provider.lookup |
Counter | {lookup} |
Number of per-client rate limit provider lookups |
hashgate.rate_limit.provider.miss |
Counter | {miss} |
Number of per-client rate limit provider lookups that fell back to default limits |
Authentication metrics include hashgate.auth.scheme, hashgate.auth.result, hashgate.client, hashgate.endpoint, and, for failures, hashgate.auth.failure_reason. Use hashgate.auth.requests grouped by hashgate.client and hashgate.endpoint to track which clients are using which API endpoints. Replay protection metrics include hashgate.replay_protection.result. Rate limit metrics include hashgate.rate_limit.policy; provider lookup metrics also include hashgate.rate_limit.provider_found.
Implement IHmacKeyProvider to load keys from your preferred storage:
public class DatabaseKeyProvider : IHmacKeyProvider { private readonly IKeyRepository _keyRepository; public DatabaseKeyProvider(IKeyRepository keyRepository) { _keyRepository = keyRepository; } public async ValueTask<string?> GetSecretAsync(string client, CancellationToken cancellationToken = default) { var key = await _keyRepository.GetKeyAsync(client, cancellationToken); return key?.Secret; } public async ValueTask<ClaimsIdentity> GenerateClaimsAsync(string client, string? scheme = null, CancellationToken cancellationToken = default) { var identity = new ClaimsIdentity(scheme); identity.AddClaim(new Claim(ClaimTypes.Name, client)); // Add additional claims based on your requirements var model = await _keyRepository.GetClientAsync(client, cancellationToken); if (model != null) { identity.AddClaim(new Claim("display_name", model.DisplayName)); // Add role claims, permissions, etc. as needed } return identity; } } // Register in DI container with custom key provider builder.Services .AddAuthentication() .AddHmacAuthentication<DatabaseKeyProvider>(); // Or register the key provider separately if needed builder.Services.AddScoped<IHmacKeyProvider, DatabaseKeyProvider>(); builder.Services.AddScoped<IKeyRepository, KeyRepository>();
The repository includes comprehensive sample implementations:
ASP.NET Core minimal API demonstrating server-side HMAC authentication:
samples/Sample.MinimalApi/dotnet run --project samples/Sample.MinimalApi.NET client implementation using HttpClient with HMAC authentication:
samples/Sample.Client/dotnet run --project samples/Sample.ClientBruno API collection demonstrating HMAC authentication:
samples/Sample.Bruno/httpYac collection demonstrating HMAC authentication:
samples/Sample.HttpYac/.http file in VS Code and send the request, or run with the httpYac CLIJavaScript/Node.js client implementation:
samples/Sample.JavaScript/npm install && npm startPython client implementation:
samples/Sample.Python/requirements.txtpip install -r requirements.txt && python demo.pyJava client implementation using the built-in java.net.http.HttpClient:
samples/Sample.Java/mvn compile && mvn exec:javahost, x-timestamp, and x-content-sha256 must be in SignedHeaders (the server enforces this). Including x-nonce (the default) is strongly recommended when replay protection is enabled"Invalid signature" errors:
"Timestamp validation failed":
ToleranceWindow if needed"Missing required headers":
host, x-timestamp, and x-content-sha256 headers are present"Replayed signature" errors when EnableReplayProtection is enabled:
x-nonce header, ensuring every signature is uniqueContributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
Version 3 introduces nonce support to guarantee per-request signature uniqueness. The x-nonce header is now included in the default signed headers.
Note: The
x-nonceheader is not required by the server. However, without it, two identical requests sent within the same second produce the same signature. BecauseEnableReplayProtectionis enabled by default, the second request will be rejected with a 401 Unauthorized response because the signature was already recorded. Includingx-nonceis strongly recommended to avoid this.
| Area | v2.x | v3.x |
|---|---|---|
| Default signed headers | host;x-timestamp;x-content-sha256 |
host;x-timestamp;x-content-sha256;x-nonce |
x-nonce header |
Not present | Optional but included by default; automatically generated (GUID) on every request |
| Replay protection | Identical requests in the same second produced the same signature | Each request has a cryptographically unique signature via nonce |
HashGate.HttpClient)If you are using the default signed headers, no code changes are required. The client automatically generates and includes x-nonce on every request.
If you have custom SignedHeaders configured, add x-nonce to the list:
services.AddHmacClient(configureOptions: options =>
{
options.Client = "MyClientId";
options.Secret = "my-secret-key";
- options.SignedHeaders = ["host", "x-timestamp", "x-content-sha256", "content-type"];
+ options.SignedHeaders = ["host", "x-timestamp", "x-content-sha256", "x-nonce", "content-type"];
});HashGate.AspNetCore)Update the NuGet package to v3.x. The server automatically recognizes x-nonce in the SignedHeaders list. No configuration changes are needed unless you have custom header validation logic.
All non-.NET clients should be updated to include x-nonce. While the server does not require it, omitting the nonce means identical requests within the same second will share the same signature and be rejected with 401 because EnableReplayProtection is enabled by default.
x-nonce header on the requestx-nonce to the SignedHeaders list in the Authorization header so the nonce value is included in the string-to-sign and the resulting signatureThis implementation is inspired by:
loresoft/HashGate is a public repo on GitHub by loresoft. HMAC Authentication Implementation for ASP.NET Core.
It declares the MIT license on GitHub.
Its maker tagged it for Windows. That is declared by the maker; Take My Repo has not tested it.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-11-11. GitHub counts 0 open issues and pull requests. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Clean Architecture Solution Template for ASP.NET Core
Roadmap to becoming an ASP.NET Core developer in 2026
ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
The Single Sign-On Multi-Factor portal for web apps. OpenID Certified™ and Post-Quantum Cryptography Ready.
Reverse engineer anything with agents, from app behavior down to native binaries.

A list of Free Software network services and web applications which can be hosted on your own servers
The MSBuild Community Tasks Project is an open source project for MSBuild tasks.
Generate Entity Framework Core model from an existing database

Source generator that helps register attribute marked services in the dependency injection ServiceCollection
A comprehensive collection of high-quality Blazor components
A library for using FluentValidation with Blazor EditForm components. Provides seamless integration between FluentValidation and Blazor forms with support for real-time validation, nested objects, async validation, and rule sets.
Calculator.NET - Calculator that evaluates math expressions
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/loresoft/HashGateTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.