← Tous les articles

SaaS: giving your customers API keys (generate, store, revoke)

Customers want to connect your SaaS to their CRM or their own scripts. Here is how we design API keys that stay safe: generation, hashed storage, narrow scopes and instant revocation, with the PHP code to match.

SaaS: giving your customers API keys (generate, store, revoke)

Key points

  • Generate keys with random_bytes() and show them exactly once.
  • Store only a SHA-256 digest, the last four characters and explicit scopes.
  • Scope every request to the key’s own tenant, and make revocation take effect immediately.

Sooner or later a SaaS customer asks to plug their own tools in: push invoices into accounting software, create contacts from a website form, feed an internal dashboard. API keys are the simplest answer for that kind of machine-to-machine access. Designed carelessly, they also become the quietest way into your data. This is the model we put in place on the applications we build.

Generating a key nobody can guess

Keys must come from a cryptographically secure source, which in PHP means random_bytes(). Not uniqid(), not a base64-encoded customer id. We add a readable prefix so a developer recognises the key in a config file, and secret-scanning tools can flag it if it ever lands in a public repository.

function create_api_key(PDO $db, int $tenantId, string $label, array $scopes): string
{
    // 32 random bytes = 64 hex chars, prefixed so leaked keys are easy to spot
    $secret = 'wts_live_' . bin2hex(random_bytes(32));

    $stmt = $db->prepare(
        'INSERT INTO api_keys (tenant_id, label, key_hash, last_four, scopes, created_at)
         VALUES (?, ?, ?, ?, ?, NOW())'
    );
    $stmt->execute([
        $tenantId,
        $label,
        hash('sha256', $secret),
        substr($secret, -4),
        json_encode($scopes),
    ]);

    return $secret; // shown once, never stored in clear
}

The full key is displayed once, at creation, with a copy button and a clear warning. If the customer loses it, they create a new one. That is by design.

Storing only a digest

Treat the key like a password: the database only ever holds a hash. For a random value of this length, SHA-256 is enough and allows a direct indexed lookup, unlike password_hash(), which is deliberately slow and salted. Keeping the last four characters in clear helps customers tell their keys apart.

function authenticate(PDO $db, string $header): ?array
{
    if (!preg_match('/^Bearers+(wts_live_[a-f0-9]{64})$/', $header, $m)) {
        return null;
    }

    $stmt = $db->prepare(
        'SELECT id, tenant_id, scopes FROM api_keys
         WHERE key_hash = ? AND revoked_at IS NULL'
    );
    $stmt->execute([hash('sha256', $m[1])]);
    $key = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$key) {
        return null;
    }

    // Cheap, useful, and lets customers spot keys nobody uses anymore
    $db->prepare('UPDATE api_keys SET last_used_at = NOW() WHERE id = ?')
       ->execute([$key['id']]);

    $key['scopes'] = json_decode($key['scopes'], true);
    return $key;
}

The last_used_at column earns its keep: customers can delete a key that has been idle for months without fear, and support can confirm in seconds whether an integration is actually calling the API.

Narrow scopes and strict tenant isolation

A key created to read invoices has no business deleting users. Simple resource:action scopes cover most needs. More importantly, the tenant is derived from the key itself, never from a parameter sent with the request.

$key = authenticate($db, $_SERVER['HTTP_AUTHORIZATION'] ?? '');

if ($key === null) {
    http_response_code(401);
    exit;
}
if (!in_array('invoices:read', $key['scopes'], true)) {
    http_response_code(403);
    exit;
}

// Every query is scoped by the key's tenant, never by a client-supplied id
$invoices = $repo->listForTenant((int) $key['tenant_id']);

The flaw we run into most often during audits: an API that validates the key properly, then reads an account_id from the URL without checking it belongs to that key. Change one digit and you are reading another customer’s data.

Revocation and rotation

Revoking a key means setting revoked_at; because every request reads the database, it takes effect at once. Allow several active keys per customer, each with a label, so they can create a new key, deploy it, then revoke the old one with zero downtime. Record creation and revocation in the account’s audit log, along with who did it.

FAQ

Should key lookups be cached?

On a busy API, a cache of a few seconds is reasonable. Keep it short, otherwise a revoked key keeps working for as long as the cache lives.

API keys or OAuth?

API keys suit integrations a customer sets up for themselves. Once third-party apps need to act on behalf of your customers, OAuth is the right tool.

Building a SaaS product and want to open an API to your customers safely? We design and build secure, documented APIs that are ready for real integrations.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →