Authentication for AI SaaS: API keys, usage limits, and agent access
An AI product has to authenticate three kinds of callers before it can answer a single prompt: the human in the dashboard, the backend service hitting the API with a key, and increasingly an autonomous agent acting on a user's behalf. Each has a different trust model, a different lifetime, and a different way of going wrong. Bolt them onto a login system designed only for humans and you end up with API keys in Slack messages, no way to meter cost per customer, and no answer when a customer asks "can my agent read but not delete?"
API keys are identities, so treat them like credentials
The quiet scandal of AI SaaS is how casually API keys are handled. They are long-lived bearer tokens that often carry full account power, and they leak constantly into Git history, CI logs, and client-side bundles. The fix is to treat each key as a first-class identity with its own scopes, owner, and lifecycle, not as a single master password for the account.
Store only a hash, show the secret exactly once, prefix the key so leak-scanners can detect it, and make rotation a routine operation rather than an emergency:
CREATE TABLE api_keys (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES tenants(id),
name text NOT NULL, -- "prod-ingest", set by the customer
prefix text NOT NULL, -- "sk_live_a1b2" shown in the UI
key_hash bytea NOT NULL, -- argon2id of the full secret
scopes text[] NOT NULL, -- ['inference:run','files:read']
rate_limit int, -- requests/min, per key
last_used_at timestamptz,
expires_at timestamptz, -- keys should expire
revoked_at timestamptz
);
CREATE INDEX ON api_keys (prefix); -- fast lookup, then verify hashsk_live_ and publish its regex so GitHub secret scanning and your own CI can catch leaks automatically. A key that announces itself is a key you can revoke the minute it hits a public repo, instead of the day a bill arrives.Metering usage per identity, not per account
AI inference costs real money per call, so "usage" is not a vanity metric; it is your margin. The problem is that a single customer account may have a dozen keys, a web session, and three agents, each generating cost. If you meter only at the account level you cannot tell a customer which integration is burning their budget, and you cannot enforce a per-key spending cap. Attribute every billable unit to the specific identity that made the call.
// Every inference call is attributed to the acting identity.
async function runInference(req: Request) {
const principal = await authenticate(req); // key, session, or agent token
await enforceLimit(principal); // per-identity rate + spend cap
const result = await model.run(req.body.prompt);
await meter.record({
tenant: principal.tenantId,
identity: principal.id, // which key/agent/user
identityKind: principal.kind,
tokensIn: result.usage.promptTokens,
tokensOut: result.usage.completionTokens,
costCents: price(result.usage),
});
return result;
}Agent access is delegation, not impersonation
The newest and hardest problem is agents. A customer wants to let an autonomous agent call your API on their behalf, but an agent is not the user and should not hold the user's full credentials. This is a delegation problem, and the right primitive is a scoped, short-lived, revocable token minted by the user, carrying a subset of their permissions and a clear record that it was delegated.
Three properties matter. The agent token must be narrower than the granting user (read-only if that is all the task needs), short-lived so a compromised agent is a transient problem, and traceable so your audit log shows both the agent and the human who authorized it. OAuth-style scopes plus an on-behalf-of claim express this cleanly.
Rate limits and spend caps as a safety feature
Humans click; agents loop. An agent in a bad state can issue thousands of calls before anyone notices, and in AI SaaS those calls cost money and can exfiltrate data at machine speed. Per-identity rate limits and hard spend caps are not just abuse protection, they are the circuit breaker that keeps one runaway agent from draining a customer's budget or your capacity. Set a default cap on every new key and agent token, and let customers raise it deliberately.
Tenancy underneath all of it
Every key, session, and agent token belongs to a tenant, and the most important guarantee is that one tenant's identity can never read another's data or usage. Carry the tenant id in the authenticated principal and enforce it at the data layer, not just the API layer, so a scoping bug cannot leak across the boundary. In a product where customers delegate access to autonomous software, tenant isolation is the thing that lets them trust the delegation at all.
AI products live and die on whether customers trust them with keys and agents, and that trust is an identity problem before it is a model problem. Owning the system that issues scoped keys, mints delegated agent tokens, and meters every call per identity, rather than renting a human-only login that charges per active user, is what lets you ship agent features without guessing at your own margins. A self-hosted identity layer like Bastionary puts those primitives under your control.
Run it yourself
Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.