October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Secure ASP.NET Core APIs with HMAC Request Signing

A practical guide to custom HMAC request authentication in ASP.NET Core, including canonicalization, handler flow, safe comparison, replay prevention, and key management.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To implement HMAC authentication in ASP.NET Core, define a request-signing format shared by client and server, then verify each request in a custom authentication handler. Use HMAC-SHA-256, compare signatures safely, and add timestamp and replay checks: HMAC proves possession of a shared secret and protects integrity, but it does not encrypt the request.

What HMAC authentication does—and does not do

HMAC is a message authentication code made with a shared secret. Microsoft describes it as a way to determine whether a message sent over an insecure channel has been tampered with, provided sender and receiver share a secret. It can authenticate message integrity and possession of that secret; it does not conceal the message contents. Use HTTPS as well. Microsoft Learn: HMAC class

As an Amazon Associate I earn from qualifying purchases.

For new designs, use HMAC-SHA-256 or stronger. Microsoft recommends SHA-256 or better because of collision problems with MD5 and SHA-1. HMACSHA256 produces a 256-bit output. Microsoft Learn: HMACSHA256 class

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

Define the signing protocol before coding

HMAC does not define an HTTP request format. Client and server must agree on exactly which bytes are signed and how those bytes are constructed. A defensible application-specific format might include the HTTP method, normalized path and query, timestamp, unique request ID, and body digest. This is a design example, not a standard format defined by ASP.NET Core or Microsoft’s HMAC APIs.

#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.

Write down these details as protocol requirements before implementing the handler:

  • Which request components are included, and in what order.
  • How fields are separated, including exact newline behavior.
  • Character encoding and any normalization for methods, paths, query strings, and header names.
  • Whether the body itself or a digest of its exact bytes is signed, and the digest format.
  • How the signature is encoded for transport, such as Base64 or hexadecimal.
  • Which timestamp format, freshness window, and request-ID rules apply.

Differences as small as URL escaping, query ordering, or a trailing newline can produce different HMAC values. Do not rely on vague instructions such as “sign the URL and body”; specify byte-for-byte behavior for both implementations.

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

Implement verification as an ASP.NET Core authentication scheme

ASP.NET Core supports custom authentication through schemes and handlers. A handler implements a scheme and, on successful authentication, creates an authentication ticket. The request validation logic belongs in that authentication flow rather than in ad hoc endpoint code. Microsoft Learn: Overview of ASP.NET Core Authentication

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Register a named scheme. Configure an authentication handler derived from AuthenticationHandler<TOptions> and register it with the application’s authentication setup.
  2. Read and validate the protocol fields. Require the key ID, timestamp, request ID, and signature headers your protocol defines. Reject missing or malformed values before attempting verification.
  3. Resolve the key by key ID. Look up the shared secret associated with the presented identifier. The key ID is not secret; never send the secret itself in a header.
  4. Reconstruct canonical bytes. Apply the exact normalization, encoding, field ordering, and body-digest rules used by clients.
  5. Compute and check the HMAC. Compute HMAC-SHA-256 from the resolved key and canonical bytes, decode the submitted signature, then compare the byte arrays using a fixed-time comparison.
  6. Apply freshness and replay checks. Reject timestamps outside the allowed window and request IDs already accepted for that key and time window.
  7. Create the authenticated identity. Only after all checks succeed should the handler return a successful authentication result with a ClaimsPrincipal and AuthenticationTicket.

Use a fixed-time signature comparison

Do not compare signature strings with ordinary equality. Decode the supplied signature, ensure it has the same byte length as the expected value, and use CryptographicOperations.FixedTimeEquals. Microsoft documents that this method avoids timing leakage from the compared values when lengths match; its runtime may still depend on input length. Microsoft Learn: FixedTimeEquals

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
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);
}

This is only the cryptographic core, not a complete handler. Key lookup and rotation, configuration, header parsing, canonicalization, body buffering, claims, failure responses, and replay protection still require application-specific implementation. Check API availability against the project’s target framework: the cited documentation spans .NET 10 API pages and a .NET Framework 4.8.1 HMACSHA256 page, so the snippet should not be assumed to compile unchanged for every ASP.NET Core target.

Prevent replay and bind signatures to the operation

A valid HMAC can be replayed: an attacker who captures a request can resend the same signed bytes. HMAC alone does not provide freshness or uniqueness. Include a timestamp and unique request identifier in the signed canonical data, enforce a narrow freshness window, and record accepted identifiers until they expire.

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.

For a multi-instance service, replay records need shared storage and an atomic check-and-insert operation; otherwise concurrent copies could pass checks on separate instances. Bind the signature to the HTTP method, path, query, and relevant content metadata so it cannot be reused for another operation. These are protocol and application responsibilities, not replay features supplied by HMAC itself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle request bodies and secrets carefully

  • Body handling: If verification reads the ASP.NET Core request stream to compute a body digest, account for buffering, stream position, and request-size limits. Ensure downstream endpoint code can still read the body as intended.
  • Secret storage: Keep shared keys out of source control and logs. Supply them through a managed secret-configuration path appropriate to the deployment.
  • Rotation: Use a key ID and maintain a controlled set of active keys so clients can transition during rotation. Plan how updated keys reach every service instance.
  • Failure behavior: Treat invalid, expired, and replayed requests as authentication failures. Avoid responses that reveal which secret-dependent check failed, and do not log secrets or sensitive full request bodies.

Require the scheme on the intended endpoints

Registering a handler does not by itself ensure every endpoint requires HMAC authentication. Configure authorization so the intended endpoints use the HMAC scheme or an authorization policy that requires it. If an application supports multiple authentication mechanisms, ASP.NET Core policy schemes can dynamically forward authentication to a selected scheme based on the request. Microsoft Learn: Policy schemes in ASP.NET Core

Best Value
FIDO2 U2F Security Key Passkey Two-Factor Authentication (2FA) USB Key PIN+Touch (Non-Biometric) USB-A Type TrustKey T110
  • Security Key : Protect your online accounts against unauthorized access by using FIDO2 and U2F authentication with T110. It's the world's most protective security key that works with windows, Mac OS, Linux as well as Chrome, Firefox, Edge and many other major browsers.
  • Certified with the new FIDO2 standard, T110 provides the benefit of fast login and strong protection against phishing, account takeover as well as many other online attactks.
  • Works with : Bank of America, Github, Google, Microsoft, DUO, Twitter, Facebook, Dropbox, Apple, ebay, BINANCE, mor and more.
  • Fits USB-A port : Insert the T110 security key into the USB-A port of each service and log in conveniently with one touch
  • For the driver download and user guide, please visit TrustKey Solutions Home support page.

When HMAC is a suitable choice

HMAC fits systems where the client can securely hold a shared secret and the server needs to verify both the client’s possession of that secret and the integrity of request components such as method, path, and body. It also brings protocol design, secret provisioning, rotation, and replay-cache responsibilities. If clients cannot keep a shared secret safe, that assumption is not met; choose an authentication design suited to that client environment rather than treating HMAC as encryption or as a complete API security system.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.