API Keys vs OAuth: Choosing API Authentication, Key Hashing and Rotation
You're opening up an API. The first customer wants to call it from a cron script on their own server. The second wants to build an app that reads data from other people's accounts. Those two requests need different credentials, and most arguments about "API keys vs OAuth" are really people picturing different callers.
The OWASP API Security Top 10 (2023) puts Broken Authentication at number two, and its prevention advice has the line that settles most of this debate: "API keys should not be used for user authentication. They should only be used for API clients authentication." Right next to it: "OAuth is not authentication, and neither are API keys." Both answer the question "may this client make this call", not "who is the human".
Start with who the caller is acting for
A customer's own code calling your API on their own account. An API key is the right tool. It's a long random secret that identifies an integration, the customer creates it in your dashboard, and it goes in a header. There's no third party to consent, so OAuth's redirect dance buys nothing.
An app acting for a user who isn't the developer. That's what OAuth exists for. The user signs in at your authorization server, approves specific scopes, and the app gets a token limited to those scopes and that user, which the user can revoke without the app ever seeing a password. Asking users to paste an API key into someone else's app is the thing OAuth replaced.
Service to service. RFC 6749's client credentials grant lets a client get an access token "using only its client credentials", it "MUST only be used by confidential clients", and the response normally carries no refresh token. Use it when you already run an authorization server and want short-lived tokens with an audience. If you don't run one, a well-managed API key is a perfectly respectable choice, and on a cloud platform the provider's workload identity may beat both.
Plenty of APIs offer both. GitHub has personal access tokens for your own scripts and GitHub Apps for integrations: its REST authentication docs recommend fine-grained personal access tokens over classic ones, and a GitHub App when acting for an organisation or another user.
API keys done properly
An API key is only as good as the boring details around it. This is the shape I'd use.
Prefix it. GitHub's post on its token formats explains why it moved to ghp_, gho_, ghu_, ghs_ and ghr_ prefixes: the old tokens were 40 hex characters "indistinguishable from other encoded data like SHA hashes". A prefix tells a scanner (and a human reading logs) what the string is, and _ isn't a Base64 character, so it rarely collides with random data. Stripe's key docs do the same with environment too: pk_test_, sk_live_, rk_live_ and so on.
Add a checksum. GitHub puts a 32-bit CRC32 checksum, Base62-encoded, in the last six characters, so a scanner can reject look-alikes offline without asking GitHub's database. GitHub's secret scanning partner program lists exactly these traits for high-quality tokens: a uniquely defined prefix, high-entropy random strings and a 32-bit checksum. Get those right and you can register a pattern with GitHub, which scans public repositories and public npm packages and POSTs any match to your endpoint so you can revoke it.
Use enough randomness, from a CSPRNG. 128 bits is a sensible floor. GitHub raised its OAuth token entropy from 160 to 178 bits with the new format.
Show it once, store a hash. Never store the key in plaintext. But don't reach for bcrypt or Argon2 either. crates.io's change to hashed tokens explains the reasoning: their tokens are truly random with 192 bits of entropy, and "unlike passwords, API tokens need to be checked on every request", so they used SHA-256. A slow password hash defends low-entropy secrets against guessing; a 190-bit random key isn't guessable, and you'd pay the slow hash on every request. OWASP's password storage cheat sheet says fast hashes like SHA-256 "are not suitable for password storage", which is right, and is about passwords. Our hash functions post covers where that line sits.
Here's all of it in about 30 lines of Node 24, no dependencies:
import { randomInt, createHash, timingSafeEqual } from 'node:crypto';
import { crc32 } from 'node:zlib';
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const base62 = (n, width) => {
let s = '';
do { s = ALPHABET[n % 62] + s; n = Math.floor(n / 62); } while (n > 0);
return s.padStart(width, '0');
};
function createKey(prefix) {
let body = '';
for (let i = 0; i < 32; i++) body += ALPHABET[randomInt(62)]; // ~190 bits, no modulo bias
return `${prefix}_${body}${base62(crc32(body), 6)}`;
}
function looksValid(key, prefix) {
const m = key.match(new RegExp(`^${prefix}_([0-9A-Za-z]{32})([0-9A-Za-z]{6})$`));
return !!m && base62(crc32(m[1]), 6) === m[2];
}
const sha256 = (s) => createHash('sha256').update(s).digest();
const key = createKey('acme_live');
const stored = { prefix: key.slice(0, 14), hash: sha256(key).toString('hex') };
const check = (presented) => looksValid(presented, 'acme_live') &&
timingSafeEqual(sha256(presented), Buffer.from(stored.hash, 'hex'));
Running it:
key shown once: acme_live_r2njj1dCeUrMGjGFKL5mcnFyr6Vhb6Z52p1mWE
stored row: {
prefix: 'acme_live_r2nj',
hash: '59423e78d7101b0b09ca9473748f18f01fcdc8b42c22ea389065377a25837ee1'
}
correct key: true
one char off: false (rejected before any DB lookup)
bits of entropy: 190.5
In a real service you'd look the row up by the hash (unique index on key_hash), so the comparison happens in the index; timingSafeEqual matters more if you ever compare secrets in application code. The display prefix is what you show in the dashboard so people can tell "acme_live_r2nj..." from their other keys.
If you just need a key for a .env file or a test fixture, our API key generator has a Prefixed format that produces sk_live_-style keys from crypto.getRandomValues. It shows the real entropy of each format; for keys you'll issue to customers, generate them server-side as above so you can add a checksum and store only the hash.
Rotation, scope and the rest of the lifecycle
Keys leak. The design question is how cheap you make recovery.
- Allow several active keys per integration. Rotation is then "create new, deploy, delete old", with no outage. When you rotate a key in Stripe's Dashboard, the old and new keys can both work for up to 7 days, and Stripe suggests watching the old key's request logs until its traffic hits zero before expiring it.
- Scope keys. Stripe now steers people away from unrestricted secret keys: they "don't recommend using secret keys for new use cases" and point to restricted keys (
rk_) with only the permissions an integration needs. Do the same: per-resource read/write scopes from day one, because adding them later means migrating every customer. - Record
last_used_at. It's how people find the keys they can delete safely. - Optional expiry and network restrictions. Stripe attaches access policies by IP range, ASN or country. Even a plain IP allowlist limits what a key pasted into a public gist can do.
- Keys in headers, never in URLs. OWASP's API2 list calls out sending "auth tokens and passwords in the URL". URLs end up in logs, browser history and
Refererheaders.
For your own side of this (where keys live in your deployments), see environment variables and secrets, and for catching leaks before they ship, the secret scanning post.
OAuth done properly, in 2026 terms
If you're issuing OAuth tokens, build to RFC 9700, the OAuth 2.0 Security Best Current Practice (BCP 240, January 2025), not to blog posts from 2015. The parts that matter most for an API provider:
- Public clients "MUST use PKCE", it's recommended for confidential clients too, and authorization servers "MUST support PKCE", preferably with S256.
- The implicit grant SHOULD NOT be used, and the resource owner password grant "MUST NOT be used".
- Access tokens should carry minimal privileges and "SHOULD be audience-restricted" to a specific resource server.
- Servers "SHOULD use mechanisms for sender-constraining access tokens", such as mutual TLS (RFC 8705) or DPoP (RFC 9449).
- Refresh tokens for public clients "MUST be sender-constrained or use refresh token rotation".
OAuth 2.1 folds most of that into the core spec. It's still a draft: draft-ietf-oauth-v2-1 reached revision -17 on 31 October 2026, with the working group's milestone set at submitting it to the IESG by December 2026. It requires PKCE, drops the implicit and password grants, and requires exact redirect URI matching. Build to it now; nothing in it conflicts with RFC 9700.
The common implementation mistakes (loose redirect matching, missing state, tokens in localStorage) have their own post: OAuth mistakes checked against RFC 9700. If your access tokens are JWTs, a JWT decoder is handy for checking aud, scope and exp while debugging, and the JWT mistakes post covers verification. Building an MCP server rather than a REST API? The remote MCP authorization post covers the OAuth profile that spec requires.
And unless running an authorization server is your product, don't write one. The auth provider comparison covers hosted and self-hosted options.
The short version, as a table
| API key | OAuth access token | |
|---|---|---|
| Who it represents | An integration on one account | A client acting for a user, within scopes |
| Who creates it | The account owner, in your dashboard | Your authorization server, after consent |
| Lifetime | Until rotated or expired | Short, refreshed |
| Revocation | Delete the key | Revoke the grant or token |
| Third-party apps | Wrong tool | What it's for |
| Cost to build | A table and a hash | An authorization server (buy one) |
| Typical failure | Leaked in a repo or log | Misconfigured redirect, missing PKCE |
My rule: ship prefixed, hashed, scoped API keys first, because almost every customer's first integration is their own script. Add OAuth on the day a third party wants to act for your users, using an existing authorization server, and keep both. Whichever you use, rate-limit per credential; the rate limiting post shows how.
Written by AIDToolStack Editorial
Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.
Sources
- api-security.owasp.org/editions/2023/en/0x11-t10
- api-security.owasp.org/editions/2023/en/0xa2-broken-authentication
- www.rfc-editor.org/rfc/rfc6749.html#section-4.4
- www.rfc-editor.org/rfc/rfc9700.html
- datatracker.ietf.org/doc/draft-ietf-oauth-v2-1/
- docs.github.com/en/rest/authentication/authenticating-to-the-rest-api
- github.blog/engineering/platform-security/behind-githubs-new-authentication-token-formats/
- docs.github.com/en/code-security/secret-scanning/secret-scanning-partnership-program/secret-scanning-partner-program
- docs.stripe.com/keys
- github.com/rust-lang/crates.io/pull/2637
- cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
Related Posts
Explore on AIDToolStack
Discover tools and servers featured in our directory.
AI Tools
MCP Servers
Sponsor Our Newsletter
Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.
All sponsored content is clearly labeled per our editorial policy.