Nov 23, 20266 min read

OAuth 2.0 Client Credentials Flow for Service-to-Service APIs

How the client credentials grant works, when it is the right flow, what a token endpoint must check, how to store client secrets and tokens, and a working token endpoint with scope checks on Encore.

Illustration for OAuth 2.0 Client Credentials Flow for Service-to-Service APIs

When one service calls another with no user in the loop, the OAuth 2.0 client credentials grant is the standard way to do it. The caller proves who it is with a client ID and secret, gets a short-lived access token, and presents that token on each API call.

The flow is short, and most of the work is in the details: the exact request and error format, how secrets are stored, and how scopes are enforced.

How does the flow work?

~
$ curl -s -u "$CLIENT_ID:$CLIENT_SECRET" \ -d "grant_type=client_credentials&scope=invoices:read" \ https://api.example.com/oauth/token{"access_token":"3f9c...","token_type":"Bearer","expires_in":3600,"scope":"invoices:read"} $ curl -s -H "Authorization: Bearer 3f9c..." https://api.example.com/invoices

RFC 6749 section 4.4 defines the grant: the client authenticates to the token endpoint, which returns an access token and, by design, no refresh token. When the token expires the client asks again. OAuth.net's summary covers when to use it.

What must the token endpoint check?

CheckResponse on failure
grant_type equals client_credentials400 with unsupported_grant_type
Client authenticates with ID and secret401 with invalid_client
Requested scope is a subset of the client's scopes400 with invalid_scope
Request is well formed400 with invalid_request

Responses are JSON with Cache-Control: no-store. Error bodies carry an error code and optionally an error_description, and nothing that reveals whether the client ID exists. Accept the credentials in an HTTP Basic header, which is the form the RFC prefers, and optionally in the request body.

How should secrets and tokens be stored?

Generate secrets and tokens from at least 32 random bytes and store only their hashes. High-entropy values do not need a slow password hash, so SHA-256 is enough, and lookups by hash stay fast. Compare with a constant-time function such as Node's timingSafeEqual, show a secret once when it is created and support two active secrets per client so they can be rotated without downtime.

Opaque tokens in a table can be revoked immediately, which JWTs cannot do without extra machinery. Use short lifetimes of an hour or less, and add a signed JWT format only if downstream services must validate tokens without calling you.

How do you enforce scopes?

Store the granted scope string with each token and copy it into the request's auth data. Each endpoint then checks for the scope it needs and returns 403 when it is missing. Keep scope names stable and specific, such as invoices:read, so a client can be limited to exactly what it needs.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and an OAuth service uses a raw endpoint for the form-encoded token request, a Postgres database for clients and tokens and an auth handler that turns a Bearer token into auth data for every endpoint marked auth: true, all declared in code.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create oauth-api --example=ts/hello-world$ cd oauth-api && mkdir -p auth/migrations

The schema

-- auth/migrations/1_create_oauth.up.sql CREATE TABLE oauth_clients ( client_id TEXT PRIMARY KEY, secret_hash TEXT NOT NULL, -- SHA-256 of the secret, hex scopes TEXT NOT NULL, -- space-separated, as in the RFC active BOOLEAN NOT NULL DEFAULT true ); CREATE TABLE oauth_tokens ( token_hash TEXT PRIMARY KEY, -- SHA-256 of the token, hex client_id TEXT NOT NULL REFERENCES oauth_clients(client_id), scope TEXT NOT NULL, expires_at TIMESTAMPTZ NOT NULL ); CREATE INDEX oauth_tokens_expiry ON oauth_tokens (expires_at);

The token endpoint and auth handler

// auth/auth.ts import { api, APIError, Gateway, Header } from "encore.dev/api"; import { authHandler } from "encore.dev/auth"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; const db = new SQLDatabase("auth", { migrations: "./migrations" }); const TOKEN_TTL_SECONDS = 3600; const sha256 = (v: string) => createHash("sha256").update(v).digest("hex"); const same = (a: string, b: string) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b)); export const token = api.raw( { expose: true, method: "POST", path: "/oauth/token" }, async (req, resp) => { const send = (status: number, body: object) => { resp.statusCode = status; resp.setHeader("Content-Type", "application/json"); resp.setHeader("Cache-Control", "no-store"); resp.end(JSON.stringify(body)); }; let raw = ""; for await (const chunk of req) raw += chunk; const form = new URLSearchParams(raw); // Prefer HTTP Basic, and accept the credentials in the body as a fallback. let clientId = form.get("client_id") ?? ""; let secret = form.get("client_secret") ?? ""; const basic = String(req.headers.authorization ?? ""); if (basic.startsWith("Basic ")) { const [id, ...rest] = Buffer.from(basic.slice(6), "base64").toString().split(":"); clientId = decodeURIComponent(id); secret = decodeURIComponent(rest.join(":")); } if (form.get("grant_type") !== "client_credentials") { return send(400, { error: "unsupported_grant_type" }); } const client = await db.queryRow<{ secret_hash: string; scopes: string; active: boolean }>` SELECT secret_hash, scopes, active FROM oauth_clients WHERE client_id = ${clientId}`; // The same error for unknown clients and wrong secrets. if (!client || !client.active || !same(client.secret_hash, sha256(secret))) { resp.setHeader("WWW-Authenticate", 'Basic realm="oauth"'); return send(401, { error: "invalid_client" }); } const allowed = new Set(client.scopes.split(" ")); const asked = (form.get("scope") ?? client.scopes).split(" ").filter(Boolean); if (asked.some((s) => !allowed.has(s))) { return send(400, { error: "invalid_scope" }); } const accessToken = randomBytes(32).toString("hex"); await db.exec` INSERT INTO oauth_tokens (token_hash, client_id, scope, expires_at) VALUES (${sha256(accessToken)}, ${clientId}, ${asked.join(" ")}, now() + make_interval(secs => ${TOKEN_TTL_SECONDS}))`; send(200, { access_token: accessToken, token_type: "Bearer", expires_in: TOKEN_TTL_SECONDS, scope: asked.join(" "), }); }, ); interface AuthParams { authorization: Header<"Authorization">; } export interface AuthData { userID: string; // the client ID scopes: string[]; } export const auth = authHandler<AuthParams, AuthData>(async (params) => { const bearer = params.authorization?.startsWith("Bearer ") ? params.authorization.slice(7) : ""; // The join means a deactivated client loses access at once, not at token expiry. const row = await db.queryRow<{ client_id: string; scope: string }>` SELECT t.client_id, t.scope FROM oauth_tokens t JOIN oauth_clients c ON c.client_id = t.client_id WHERE t.token_hash = ${sha256(bearer)} AND t.expires_at > now() AND c.active`; if (!bearer || !row) throw APIError.unauthenticated("invalid or expired token"); return { userID: row.client_id, scopes: row.scope.split(" ") }; }); export const gateway = new Gateway({ authHandler: auth });
// invoices/invoices.ts import { api, APIError } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; export const list = api( { expose: true, auth: true, method: "GET", path: "/invoices" }, async (): Promise<{ invoices: string[] }> => { if (!getAuthData()!.scopes.includes("invoices:read")) { throw APIError.permissionDenied("missing scope invoices:read"); } return { invoices: [] }; }, );

encore run starts a local Postgres and serves both endpoints, so you can run the curl calls from the top of this article against localhost:4000. On deploy, the database runs on RDS or Cloud SQL and Encore provisions an IAM role for the service, or a service account on GCP, as the AWS and GCP infrastructure docs describe. A coding agent adding a protected endpoint marks it auth: true and checks a scope in the same change, and the auth handler already runs in its local tests.

Best fit: Teams exposing an API to partner services or internal jobs that want short-lived, scoped tokens without running a separate identity server.

Things to decide early

  • Token format. Keep opaque tokens while only your own API validates them, and issue JWTs only when other services must validate offline.
  • Rotation. Allow two active secrets per client, and expire old ones on a schedule.
  • Cleanup. Delete expired rows from the tokens table with a daily job, which in Encore is a cron job managed by the platform that does not run locally.
  • Rate limiting. Limit failed token requests per client ID and per IP to slow down secret guessing.

Frequently asked questions

What is the OAuth 2.0 client credentials flow?

It is the grant for machine-to-machine access with no user involved. A client authenticates to the token endpoint with its client ID and secret and receives an access token, which it sends as a Bearer token to the API. RFC 6749 defines it in section 4.4.

When should you use client credentials instead of an API key?

Use it when you want short-lived tokens, scopes per client and a standard interface that clients and gateways already support. A plain API key is simpler and fine for a few trusted callers, but it is long-lived and usually all-or-nothing.

How should client secrets and access tokens be stored?

Store only a hash of each. For secrets and tokens generated as long random values a SHA-256 hash is enough, and you compare hashes with a constant-time function. Show the secret once at creation and never log it.

How do you build a client credentials token endpoint with Encore?

With Encore, declare a raw endpoint for POST /oauth/token, a Postgres database for clients and tokens, and an auth handler that resolves Bearer tokens. Encore provisions the database in your AWS or GCP account and runs the auth handler for every endpoint marked auth.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders