Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

To implement HMAC authentication in ASP.NET Core, define a request-signing format shared by client and server, then register a custom authentication scheme that verifies each request and issues an authenticated ticket only when the signature is valid. Use HMAC-SHA-256, compare signatures in fixed time, and add timestamp and replay checks: HMAC proves possession of a shared secret and protects integrity, but it does not encrypt traffic or prevent replay by itself.

What HMAC authentication does—and what it does not do

Microsoft Learn describes HMAC as a way to determine whether a message sent over an insecure channel has been tampered with, provided sender and receiver share a secret key. HMAC does not conceal the message contents, so protect API traffic with HTTPS as well. See Microsoft’s HMAC class documentation.

For an API request, the client computes a keyed digest over agreed request data and sends the signature with the request. The server rebuilds the same bytes using the shared secret and compares its result with the supplied signature. A valid signature establishes that a party possessing the key signed those bytes and that they have not changed; it does not identify a particular person unless the application maps the key to an identity.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define the signing protocol before writing the handler

ASP.NET Core provides authentication infrastructure, but the cited Microsoft documentation does not define a standard HMAC request format. You must specify one that both client and server implement identically. For example, a canonical request could include:

#1 Best Overall
Yubico - Security Key C NFC - Basic Compatibility - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key C NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key C NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key C NFC via USB-C and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.
  • The HTTP method in uppercase.
  • A consistently normalized path and query string.
  • A timestamp and unique request identifier.
  • A digest of the request body.

Also decide the exact separators, character encoding, newline rules, URL normalization, header names, signature encoding, and body-digest format. Ambiguity in any of these can make valid client signatures fail—or leave parts of a request unsigned. Bind the signature to the method, path, query, body, and any content metadata that matters to the operation.

Implement the cryptographic core

Prefer HMAC-SHA-256. Microsoft documents HMACSHA256 as producing a 256-bit output and recommends SHA-256 or better rather than MD5 or SHA-1 because of collision problems. The following illustrates only signature computation and comparison; it is not a complete authentication handler.

Rank #2
Yubico - YubiKey 5C NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5C NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5C NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5C NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts
using System.Security.Cryptography;

static byte[] ComputeSignature(byte[] secret, byte[] canonicalRequest)
{
    return HMACSHA256.HashData(secret, canonicalRequest);
}

static bool SignatureMatches(byte[] expected, byte[] supplied)
{
    return expected.Length == supplied.Length &&
        CryptographicOperations.FixedTimeEquals(expected, supplied);
}

Verify API availability for your project’s target framework. The cited documentation covers multiple .NET versions, and this sample should not be assumed to compile unchanged on every ASP.NET Core target. For algorithm details, see Microsoft’s HMACSHA256 API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add a custom ASP.NET Core authentication handler

ASP.NET Core authentication is organized around schemes and handlers. A handler processes authentication for its scheme and, on success, creates an authentication ticket. Follow the framework’s authentication overview for the scheme and handler model.

Rank #3
Yubico - YubiKey 5 NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-A or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5 NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5 NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5 NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts
  1. Register a named scheme. Configure the custom handler with `AddScheme` and the options type used by your application. Choose a scheme name that can be referenced by endpoint policies.
  2. Parse and validate required headers. Reject requests with missing or malformed key IDs, timestamps, request identifiers, or signatures before attempting verification.
  3. Resolve the key. Use the presented key ID to look up the corresponding active secret. The key ID is not secret; never send the secret itself in a header.
  4. Reconstruct canonical bytes. Apply the exact method, URL, body digest, and encoding rules agreed by client and server.
  5. Verify the signature. Compute the expected HMAC and compare decoded signature bytes using `CryptographicOperations.FixedTimeEquals` after confirming lengths match.
  6. Apply freshness and replay checks. Validate the timestamp and atomically record the request identifier if it has not already been accepted.
  7. Issue an identity only on success. Create the application’s claims principal and authentication ticket only after every validation passes. Return authentication failure otherwise.

Microsoft documents FixedTimeEquals as comparing equal-length buffers without leaking timing information through the compared values. The method’s runtime may still depend on input length, which is why checking equal lengths first is appropriate.

Prevent replay attacks

A correctly signed request can still be copied and sent again: HMAC authenticates the same bytes each time. Include a timestamp and unique request identifier in the canonical data, reject timestamps outside a narrow freshness window, and store accepted identifiers for that window. In a multi-instance service, use shared replay state; the check-and-record operation must be atomic so concurrent copies cannot both pass.

Rank #4
Yubico - Security Key NFC - Basic Compatibility - Multi-Factor Authentication (MFA) Key, Connect via USB-A or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key NFC via USB-A and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

Handle keys and request bodies safely

  • Protect secrets. Keep keys out of source control, application logs, and client-visible headers. Load them through a managed secret configuration path.
  • Plan rotation. Associate each signature with a key ID and accept only a controlled set of active keys. Coordinate key distribution across service instances and define when old keys stop being accepted.
  • Account for body reading. If the handler or middleware reads the request stream to hash the body, account for buffering, stream position, and request-size limits so downstream code can still process the request.
  • Limit failure detail. Treat invalid signatures, expired timestamps, and replayed identifiers as authentication failures. Do not reveal which secret-dependent check failed, and avoid logging secrets or full sensitive bodies.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Require the scheme on the intended endpoints

Registering a handler does not by itself ensure every relevant endpoint requires HMAC. Apply an authorization policy that names the HMAC scheme to the endpoints that need it. If an application supports multiple authentication mechanisms, ASP.NET Core policy schemes can dynamically forward authentication to a scheme based on the request; see Microsoft’s policy schemes documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a custom HMAC scheme is a good fit

HMAC is useful when a client can safely protect a shared secret and the API needs request integrity tied to the method, path, and body. It brings protocol and operational work that a basic authentication mechanism may not: client key provisioning, canonicalization, rotation, replay state, and consistent implementation on both sides. Choose it when those controls and request binding are requirements, not merely because a custom signature sounds stronger.

Best Value
Yubico - YubiKey 5C - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB, FIDO Certified - Protect Your Online Accounts (5C)
  • POWERFUL SECURITY KEY: The YubiKey 5 is a versatile physical passkey that protects your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5 secures 100+ of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5 via USB and tap it to authenticate. No batteries, no internet connection, and no extra fees required.
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.