How-To Guide

How to Implement Signed URLs for Temporary Access

Generate signed URLs that grant narrow, time-boxed access to objects: sign the exact method and path, set expiry, and verify without leaking secrets.

On this page

  1. Introduction
  2. Sign exactly the operation you grant
  3. Set and embed the expiry
  4. Verify in constant time and check expiry
  5. Scope the grant and rotate secrets
  6. Test tampering and expiry
  7. Common pitfalls
  8. Conclusion

Introduction

Sometimes a client needs temporary access to a resource it should not be able to reach permanently: a user downloading their own export, an uploader writing to a staging bucket, or a partner fetching a one-time report. Issuing credentials for each case is heavy and risky. A signed URL solves it: the server grants a narrow, time-boxed capability by signing a specific operation with a secret only it holds, and the recipient uses the URL without ever seeing that secret.

This tutorial builds a signed URL scheme for object access. It covers what to include in the canonical string, how to bind the signature to the method and path, how to handle expiry, how to verify without leaking the secret through timing, and the tests that prove tampering and expiry are rejected. The examples use HMAC, but the design is the same for any signing scheme.

Sign exactly the operation you grant

The signature must cover everything that matters to the decision, or an attacker can take a signature for one operation and apply it to another. At minimum, bind the HTTP method, the host, the path, and the expiry. If the request carries other security-relevant parameters, such as a content type for uploads or a version id for the object, include them too. A common failure is signing only the path, which lets a signed GET be replayed as a DELETE.

Assemble a canonical string deterministically: the parts in a fixed order, each with its own delimiter, and no ambiguity about where one part ends and the next begins. Sort or fix the order of any optional parameters, and normalize the path so a trailing slash or a percent-encoding difference does not create two signatures for one target. The same canonicalization must be used when signing and when verifying, or the two will disagree on a valid request.

import { createHmac, timingSafeEqual } from 'node:crypto';

function canonical(method, host, path, expiresAt) {
  return [method.toUpperCase(), host, path, String(expiresAt)].join('\n');
}

function sign(secret, method, host, path, expiresAt) {
  return createHmac('sha256', secret)
    .update(canonical(method, host, path, expiresAt))
    .digest('base64url');
}

Set and embed the expiry

Give every signed URL the minimum lifetime the use case requires. An export download might need a few minutes; a partner report might need a few hours. Shorter is safer: a leaked URL is useful only until it expires. Use an absolute expiry, not a sliding window, so the lifetime does not extend with use. Embed the expiry in the signed payload so a client cannot change it; if the expiry is an unsigned query parameter, editing it extends the ability to use the URL.

Store the expiry as a Unix timestamp in seconds and compare against the server clock at verification time. Reject a request whose expiry is in the past, and return a distinct error for expiry so the client can distinguish a stale link from a tampered one. Clamp the maximum expiry in the issuer so a caller cannot request a ten-year link.

function issueSignedUrl(secret, method, host, path, ttlSeconds) {
  const expiresAt = Math.floor(Date.now() / 1000) + Math.min(ttlSeconds, 3600);
  const signature = sign(secret, method, host, path, expiresAt);
  const url = new URL(path, 'https://' + host);
  url.searchParams.set('expires', String(expiresAt));
  url.searchParams.set('sig', signature);
  return url.toString();
}

Verify in constant time and check expiry

Verification recomputes the canonical string from the incoming request and compares the result to the supplied signature using a constant-time comparison. A naive string equality returns as soon as it finds a difference, which leaks how many leading bytes matched and can allow an attacker to recover a signature byte by byte. Use a constant-time comparison function, and compare equal-length buffers to avoid a length error.

Check expiry before or alongside the signature, and decide the order deliberately. Verifying the signature first prevents an attacker from probing expiry handling with forged signatures, but recomputing the signature on expired requests wastes work. A common approach is to parse and validate expiry format cheaply, verify the signature, then enforce the expiry. Return distinct, non-leaky errors: a generic 403 for a bad signature and a specific message for expiry are both acceptable, but the response must not reveal the secret or the internal canonical string.

function verify(secret, req) {
  const url = new URL(req.url, 'https://' + req.headers.host);
  const expiresAt = Number(url.searchParams.get('expires'));
  const supplied = url.searchParams.get('sig') ?? '';
  if (!Number.isInteger(expiresAt)) return { ok: false, reason: 'bad-request' };
  const expected = sign(secret, req.method, req.headers.host, url.pathname, expiresAt);
  const a = Buffer.from(expected);
  const b = Buffer.from(supplied);
  if (a.length !== b.length || !timingSafeEqual(a, b)) return { ok: false, reason: 'bad-signature' };
  if (expiresAt < Math.floor(Date.now() / 1000)) return { ok: false, reason: 'expired' };
  return { ok: true };
}

Scope the grant and rotate secrets

A signed URL should grant the narrowest operation that satisfies the use case. Sign a single object path and a single method rather than a prefix that covers many objects. Where the risk is high, require additional authorization beyond the signature, such as a session that proves the caller is the owner, so a leaked link is not sufficient on its own. Never let a signature authorize an operation that is destructive and hard to undo without a second check.

Rotate the signing secret periodically and support two active secrets during rotation so URLs issued under the old secret still verify until they expire. Do not reuse the signing secret for other purposes; a dedicated key per use limits the blast radius of a leak. Store the secret in a secret manager and load it at startup, never in source control.

Test tampering and expiry

Test the adversarial cases explicitly. Mutate the path and assert the signature fails. Change the method and assert it fails, proving the method is bound. Extend the expiry parameter and assert the signature fails, proving the expiry is signed. Use a valid signature with an expiry in the past and assert the specific expiry error. Finally, assert that a valid signature for one object cannot be used on another path.

curl -s -o /dev/null -w '%{http_code}\n' "$SIGNED_URL"
curl -s -o /dev/null -w '%{http_code}\n' "$(echo "$SIGNED_URL" | sed 's#/report#/secret#')"
curl -s -o /dev/null -w '%{http_code}\n' "$(echo "$SIGNED_URL" | sed 's/expires=[0-9]*/expires=9999999999/')"

Common pitfalls

Signing only the path so the method can change, leaving the expiry unsigned, comparing signatures with a non-constant-time function, granting a prefix instead of a single object, using one long-lived secret forever, and putting the signing secret anywhere near the URL are the recurring mistakes. Each is blocked by the canonical-string rule, the embedded expiry, the constant-time compare, and secret rotation.

Conclusion

A signed URL is a narrow, time-boxed capability. Sign a canonical string that binds method, host, path, and expiry, embed the expiry so it cannot be edited, compare signatures in constant time, and scope the grant to one operation. Self-check by tampering with the path, the method, and the expiry and asserting each is rejected, and by verifying that expiry yields its own error. Done right, temporary access never means broadcasting a secret.

Sources: AWS: Presigned URLs, RFC 2104: HMAC, OWASP: Cryptographic storage cheat sheet.

FAQ

What should a signed URL never contain?
It should never contain the signing secret itself, and the signature should not be the sole authorization for a broadly destructive action. Sign the narrow operation, not the whole account, and check other authorization besides the signature where the risk warrants.
Expiry in the URL or in the signature?
Put the expiry inside the signed payload so it cannot be changed without invalidating the signature. If the expiry is a separate query parameter that is not signed, a client can extend it by editing the URL.

Related Examples