Prompt
I'm building a B2B API how do I set up auth and keys
Latest observation
For a B2B API, the usual pattern is:
- Human admins/authors: use OAuth 2.0 / OIDC with your app
- Server-to-server customers: use API keys or, better, client credentials with OAuth 2.0
- Fine-grained access: add scopes/roles and tenant isolation
Here’s a practical setup that works well.
1) Pick the auth model by use case
A. Customer systems calling your API
Best options:
Option 1: OAuth 2.0 Client Credentials
Use when a customer’s backend service integrates with your API.
- You issue:
client_idclient_secret
- Their server exchanges them for an access token
- Token expires quickly, usually 5–60 minutes
Pros
- Short-lived tokens
- Easy to revoke
- Better security than long-lived API keys
Cons
- Slightly more complex than API keys
Option 2: API keys
Use when you want simplicity and the customer is mostly machine-to-machine.
- You issue a long-lived key
- They send it on each request, often as a header:
Authorization: Bearer <api_key>- or
X-API-Key: <key>
Pros
- Simple
- Easy to implement
Cons
- Harder to secure
- Usually over-privileged
- Long-lived secrets are risky
Recommendation: If you can, prefer OAuth client credentials. If you need a simpler first version, start with API keys but design the system so you can migrate to OAuth later.
2) Separate “account” from “credentials”
For B2B, each customer should have:
- a tenant/org
- one or more service accounts
- one or more credentials for those service accounts
Example structure:
- Tenant:
acme - Service account:
acme-prod-sync - Credentials:
- API key
sk_live_... - or OAuth client
client_id,client_secret
- API key
This lets you:
- rotate keys without breaking all integrations
- give different credentials different permissions
- audit actions by credential
3) Store only hashed secrets
For API keys and client secrets:
- show the secret only once at creation time
- store only a hash server-side, not the raw secret
- use a strong one-way hash like:
- bcrypt
- scrypt
- Argon2
- or HMAC with a server-side pepper if you need lookup optimization
Common pattern
Generate a secret like:
- prefix for identification:
sk_live_ - random secret payload: 32+ bytes base64url/hex
Example:
sk_live_7f3a...
Store:
key_idor prefix metadata- hashed secret
- tenant ID
- scopes
- status
- expiration
- last used at
When a request comes in:
- parse key ID/prefix
- find candidate record
- verify hash
- check tenant, scopes, status, expiry
4) Use scoped permissions
Don’t make one key do everything.
Examples of scopes:
read:customerswrite:ordersread:invoiceswebhooks:manage
Or use roles:
adminread_onlybilling_sync
Scopes are usually better for APIs because they’re more explicit.
5) Add tenant isolation everywhere
Every request should resolve to exactly one tenant/org.
Your auth middleware should attach:
tenant_idcredential_idscopes
Then every DB query should filter by tenant_id.
Never trust a tenant ID passed by the client alone unless it is cryptographically tied to the authenticated credential.
6) Use HTTPS only
This is non-negotiable.
- require TLS everywhere
- reject plain HTTP
- consider HSTS for browser-facing admin portals
7) Make keys easy to rotate and revoke
You need:
- multiple active keys per customer
- ability to revoke one key without breaking others
- optional expiry dates
- audit log of:
- created
- last used
- revoked
- rotated
Good lifecycle:
- create new key
- customer updates integration
- verify new key works
- revoke old key
8) Consider signing requests for extra security
If you need stronger protection against replay attacks or leaked traffic, use request signing.
Pattern:
- customer gets
key_id+secret - each request includes:
- timestamp
- nonce
- signature over method/path/body/timestamp
- server verifies signature and rejects old timestamps/reused nonces
This is more work, but useful for high-security integrations.
If you want simpler, use short-lived access tokens via OAuth instead.
9) Recommended architecture for a modern B2B API
Best-practice setup
- OIDC/OAuth for user login
- OAuth 2.0 client credentials for service integrations
- JWT access tokens or opaque tokens
- scopes for permissions
- refresh tokens only if needed for human users
- admin portal for managing credentials
If you want a simpler v1
- API keys for machine integrations
- admin portal to create/revoke keys
- hashed storage
- scopes
- rate limits
- audit logs
- later migrate to OAuth
10) Essential security controls
Add these from day one:
- rate limiting per key/tenant
- IP allowlisting for enterprise customers if useful
- audit logs
- secret rotation
- least privilege scopes
- anomaly detection for abuse
- request size limits
- signed webhooks for outbound events
- key revocation and expiration
11) Example API key format
A good key format:
- prefix identifies environment/type
- public ID for lookup
- secret part for verification
Example:
sk_live_pub_12345.secretpart
Or simpler:
sk_live_2f8c1b7e9d4a...
Store:
public_id- hashed secret
This lets you find the record quickly without brute-forcing every stored hash.
12) Example flow
Creating a key
- Admin logs into your portal
- Chooses “Create API credential”
- System generates secret once
- Store hashed secret
- Show credential to user once
Authenticating a request
- Client sends
Authorization: Bearer <token> - Server validates token/API key
- Attach tenant + scopes
- Authorize endpoint access
- Log usage
13) What I’d recommend for you
If you’re early-stage and B2B:
Option A: Strong default
- OAuth 2.0 client credentials for service-to-service
- OIDC for human login
- scopes + tenant isolation
- hashed secret storage
- key rotation and revocation
Option B: Fastest MVP
- API keys only
- one key per service account
- hashed storage
- scopes
- admin portal
- rate limiting
- plan to add OAuth later
14) Don’t do these
- don’t use one global shared API key
- don’t store secrets in plaintext
- don’t put keys in query strings
- don’t let clients choose their own tenant ID without verification
- don’t make keys perpetual with no rotation path
- don’t use the same key for all environments
If you want, I can give you one of these next:
- a database schema for API keys and tenants
- a Node/Express auth middleware example
- a Python/FastAPI example
- a full OAuth client credentials design for B2B APIs