API Security
.
12
Mins Read

Machine-to-Machine API Authentication with Client Credentials

Machine identities now outnumber people 82 to 1, and every one needs to prove who it is. This guide explains machine-to-machine authentication with the OAuth client credentials flow: how it works, how clients should authenticate, cache and scope tokens, how to rotate secrets or drop them entirely, and how it applies to AI agents, with tested code.

Dhayalan Subramanian
Associate Director - Product Growth at DigitalAPI
.
20 November 2026
In this blog
Share blog
TL;DR:

What is the client credentials flow?

The client credentials flow is the OAuth 2.0 grant that lets a machine, such as a back-end service, batch job or AI agent, get an access token using its own identity, with no user involved.

The client authenticates to the authorization server with a secret, a signed JWT or a certificate, receives a short-lived token for one API, and sends it with each call.

No refresh token is issued.

Machine identities now outnumber human identities 82 to 1, according to CyberArk's 2025 Identity Security Landscape report. The same research found 42% of those machine identities have privileged or sensitive access.

Every one of those services, scripts and agents needs to prove who it is before it calls an API. For most of them, the answer is the client credentials flow. It's simple to set up and easy to get wrong: a shared secret pasted into a config file, a token requested on every call, a scope that covers everything.

This guide explains how machine to machine authentication with client credentials works, how clients should authenticate, cache and scope their tokens, how to rotate secrets or get rid of them, and how it applies to AI agents, with code we ran and tested.

Client credentials flow infographic showing a machine client authenticating to the authorization server, receiving a short-lived scoped access token, caching it, and calling the API, with the client authentication methods ranked from shared secrets to workload identity federation

What is machine-to-machine (M2M) authentication?

Machine-to-machine authentication is how one piece of software proves its identity to another, with no person involved. A billing service calling an invoices API, a nightly export job, a partner's back end and an AI agent all need M2M authentication.

The main options are:

Machine-to-machine authentication methods compared

MethodHow the machine proves who it isStrengthTypical use
API keySends a long-lived static keyWeak: never expires on its own, often sharedLow-risk public APIs, quotas
Client credentials with a secretSwaps a client ID and secret for a short-lived tokenMedium: the secret is still staticMost internal and partner services
Client credentials with private_key_jwtSigns a short assertion with a private keyStrong: the private key never leaves the clientPartner and high-value APIs, open banking
Client credentials with mTLSProves possession of a certificate in the TLS handshakeStrong, and tokens can be bound to the certificatePayments, regulated APIs, service meshes
Workload identity federationUses a token from its platform (Kubernetes, cloud, CI) instead of any stored secretStrongest: no long-lived secret at allCloud workloads, CI/CD pipelines

Swipe sideways to see all columns →

The last four all use OAuth. They differ only in how the client authenticates to the authorization server, which turns out to be the most important decision in service to service authentication.

What is the client credentials flow?

The client credentials flow is an OAuth 2.0 grant type in which a client requests an access token for itself, using only its own credentials, to call APIs it has been allowed to use. There's no user, no browser redirect and no consent screen.

Definition

Client credentials flow

The client credentials flow, or client credentials grant, is the OAuth 2.0 grant defined in RFC 6749 section 4.4 that lets a confidential client obtain an access token by authenticating directly to the authorization server's token endpoint. The token represents the client itself, not a user, and is used for machine-to-machine access to APIs the client has been authorized to call.

Three rules from the standard shape everything else:

  • Only confidential clients may use it. The client must be able to keep a credential secret, which rules out browser apps and mobile apps.
  • The token represents the client, not a user. Permissions come from what the client is registered for, not from anyone's consent.
  • No refresh token. RFC 6749 says a refresh token should not be issued, because the client can request a new access token whenever it needs one.

What is the difference between client credentials and authorization code?

Use the authorization code flow when a user signs in and grants access; use the client credentials flow when a machine acts on its own behalf. That's the whole of client credentials flow vs authorization code in one line.

Client credentials vs authorization code

 Client credentialsAuthorization code (with PKCE)
Who the token representsThe client applicationA user, via the client
User presentNoYes, signs in and consents
Browser redirectNoYes
Refresh tokenNoUsually
Suitable clientsBack-end services, jobs, server-side agentsWeb, mobile and desktop apps
ExampleBilling service reads all invoicesA partner app reads one user's invoices

Swipe sideways to see all columns →

If you're new to OAuth itself, start with what is OAuth.

How does the client credentials flow work?

The client credentials flow has four steps: the client authenticates to the token endpoint, the authorization server checks it and issues a scoped token, the client calls the API with the token, and the API validates it. When the token expires, the client repeats step one.

  1. Request a token. The client sends grant_type=client_credentials to the token endpoint, with the scopes and API (resource) it needs, and authenticates itself.
  2. Issue the token. The authorization server verifies the client, checks the requested scopes and API against what the client is registered for, and returns a short-lived access token.
  3. Call the API. The client sends the token in the Authorization: Bearer header.
  4. Validate. The API, or the API gateway in front of it, checks the token's signature, issuer, audience, expiry and scope.

Here's the token request with a client secret, sent in the Authorization header (client_secret_basic):

HTTP · client credentials token request
POST /oauth/token HTTP/1.1
Host: auth.example.com
Authorization: Basic YmlsbGluZy1zdmM6czNjcjN0
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&scope=invoices:read&resource=https://api.example.com/invoices

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store

{ "access_token": "eyJhbGciOiJFUzI1NiIsInR5cCI6ImF0K2p3dCJ9...", "token_type": "Bearer", "expires_in": 300, "scope": "invoices:read" }

Note what's missing: there's no refresh_token. The resource parameter (RFC 8707) names the one API the token is for, so the token can't be replayed against another API.

Client credentials flow sequence diagram showing a machine client sending a signed client assertion to the authorization server, receiving a scoped access token with no refresh token, caching it, calling the API with the bearer token, and requesting a new token shortly before expiry

How should a machine client authenticate to the token endpoint?

Prefer authentication that doesn't rely on a shared secret: private_key_jwt, mTLS, or workload identity federation. A client secret works, but it's a static password that has to be stored, shared with the authorization server and rotated by hand.

How a machine client can authenticate to the token endpoint

MethodWhat the client sendsWhat leaks if the client is compromisedNotes
client_secret_basicClient ID and secret in the Authorization: Basic headerThe secret, usable from anywhere until rotatedThe default; acceptable for low-risk internal APIs
client_secret_postClient ID and secret in the request bodySame as aboveAvoid; never put secrets in query strings
private_key_jwt (RFC 7523)A JWT signed with the client's private keyNothing reusable: each assertion expires in seconds and works onceServer stores only the public key
tls_client_auth / self_signed_tls_client_auth (RFC 8705)A client certificate during the TLS handshakeNothing reusable without the private keyTokens can be bound to the certificate
Workload identity federationA token from the platform the workload runs onNothing stored on diskNo secret to rotate at all

Swipe sideways to see all columns →

With private_key_jwt, the authorization server never holds anything a thief could use to impersonate the client. It stores only the client's public key, and each signed assertion works once. Here's how the token endpoint verifies both a secret and a signed assertion:

Node.js · token-server.mjs (excerpt)
// token-server.mjs (excerpt): authenticate the client by secret or by signed assertion
async function authenticateClient(req) {
  const b = req.body;
  if (b.client_assertion_type === 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer') {
    const claimed = clients[decodeJwt(b.client_assertion).iss];          // look up the key the client registered
    if (!claimed?.publicKey) throw new Error('invalid_client');
    const { payload } = await jwtVerify(b.client_assertion, claimed.publicKey,
      { audience: url, algorithms: ['ES256'], maxTokenAge: '5m' });     // signature, audience, freshness
    if (payload.iss !== payload.sub || !clients[payload.iss]) throw new Error('invalid_client');
    if (seenJti.has(payload.jti)) throw new Error('invalid_client');   // replay
    seenJti.set(payload.jti, payload.exp);
    return payload.iss;
  }
  const [id, secret] = Buffer.from((req.headers.authorization || '').replace(/^Basic /, ''), 'base64').toString().split(':');
  const c = clients[id];
  if (!c?.secretHash || !timingSafeEqual(hash(secret || ''), c.secretHash)) throw new Error('invalid_client');
  return id;
}

Four checks matter: the assertion is signed by the key the client registered, its audience is this token endpoint, it's no more than five minutes old, and its jti hasn't been seen before. The secret path stores only a hash of the secret and compares it in constant time.

What is workload identity federation?

Workload identity federation lets a workload authenticate with a token its platform already gives it, such as a Kubernetes service account token or a GitHub Actions OIDC token, instead of a stored secret. The authorization server trusts the platform's issuer and exchanges that token for an access token.

It's the end state for machine authentication because there's nothing to leak, store or rotate. The platform issues short-lived identity tokens automatically. Google Cloud, Microsoft Entra, AWS and most identity providers support it, using the JWT bearer pattern from RFC 7523 or OAuth token exchange (RFC 8693). Use it for cloud workloads and CI/CD pipelines; use private_key_jwt or mTLS where federation isn't available, such as partner back ends.

How should a client cache and reuse its access token?

Request a token once, reuse it until shortly before it expires, and make sure many simultaneous calls trigger only one token request. Requesting a token per API call is the most common client credentials mistake. It slows every call, loads the authorization server, and hits token endpoint rate limits.

Here's a client that authenticates with private_key_jwt and caches its token:

Node.js · token-client.mjs
// token-client.mjs: a machine client that authenticates with private_key_jwt and caches its token
// Node.js 18+, jose 5.x
import { SignJWT } from 'jose';
import { randomUUID } from 'node:crypto';

export function tokenClient({ tokenUrl, clientId, privateKey, kid, scope, resource, skewSeconds = 60 }) {
  let cached = null, inflight = null;

  async function fetchToken() {
    // RFC 7523 client assertion: short-lived, single-use (jti), audience = the token endpoint
    const assertion = await new SignJWT({}).setProtectedHeader({ alg: 'ES256', kid })
      .setIssuer(clientId).setSubject(clientId).setAudience(tokenUrl)
      .setIssuedAt().setExpirationTime('60s').setJti(randomUUID()).sign(privateKey);
    const res = await fetch(tokenUrl, { method: 'POST',
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ grant_type: 'client_credentials', scope, resource,
        client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', client_assertion: assertion }) });
    const body = await res.json();
    if (!res.ok) throw new Error(body.error);
    cached = { token: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 };
    return cached.token;
  }

  // Reuse the token until shortly before it expires; one request even if many calls arrive at once
  return async function getToken() {
    if (cached && Date.now() < cached.expiresAt - skewSeconds * 1000) return cached.token;
    inflight ??= fetchToken().finally(() => { inflight = null; });
    return inflight;
  };
}

The skewSeconds margin renews the token a minute before it expires, so a call never leaves with a token that dies in flight. The inflight promise means 50 calls arriving at once share one token request instead of making 50.

What happened when we tested the client credentials flow?

We ran the token endpoint and client above with Node.js 18+ and jose 5.9.6. Every result matched what the flow should do:

Client credentials flow test results

TestResult
client_secret_basic with the right secret200: access token, no refresh token
client_secret_basic with a wrong secret401 invalid_client
100 API calls (50 at once, then 50 in sequence) through the caching client1 token request; the same token reused for all 100
Fresh private_key_jwt assertion200
Same assertion sent again (replay)401 invalid_client: jti already used
Assertion addressed to a different token endpoint401 invalid_client: wrong audience
Assertion signed with a key the client didn't register401 invalid_client
Request for a scope the client isn't registered for400 invalid_scope
Request for a token for a different API400 invalid_target

Swipe sideways to see all columns →

Client credentials flow test results showing secret and private_key_jwt client authentication, a replayed assertion rejected, 100 API calls served by one cached token, and invalid scope and invalid target errors

How do you scope machine-to-machine tokens?

Give every workload its own client, register only the scopes and APIs it needs, and request one API per token. A client credentials token acts with the client's full registered access every time, with no user to limit it, so the registration is the only boundary.

  • One client per workload. Never share a client ID between the billing service, the export job and an agent. You can't revoke one without breaking the others, and logs can't tell them apart.
  • Narrow scopes. Register invoices:read, not invoices:*. See OAuth scopes explained for scope design.
  • One audience per token. Use the resource parameter so a token for the invoices API fails on the payroll API.
  • Short lifetimes. Five to 60 minutes. There's no refresh token to protect, so there's no reason to issue long-lived access tokens.
  • Object-level checks still apply. A token with invoices:read should still only read the tenant's own invoices. See API authorization.

These are the machine side of the principle of least privilege: every client should be able to do one job and nothing else.

How do you secure and rotate client secrets?

Store client secrets in a secrets manager, never in code or config files, and rotate them with an overlap period so nothing breaks. Better still, replace them with private_key_jwt, mTLS or workload identity federation.

Secrets leak constantly. GitGuardian's State of Secrets Sprawl 2025 found 23.8 million new secrets pushed to public GitHub repositories in 2024, and 70% of secrets leaked in 2022 were still valid two years later. A client secret that never rotates is a credential that never expires.

  1. Generate secrets with high entropy, at least 32 random bytes, and show them only once.
  2. Store them in a secrets manager such as HashiCorp Vault, AWS Secrets Manager or Azure Key Vault, injected at runtime.
  3. Store only a hash on the authorization server, as our test server does.
  4. Rotate with overlap: issue a second secret, deploy it, confirm traffic has moved, then revoke the first. Two active secrets per client make zero-downtime rotation possible.
  5. Rotate on a schedule, every 90 days or less, and immediately after any suspected leak or staff change.
  6. Never send secrets in URLs or query strings, where they end up in logs.
  7. Scan repositories and logs for leaked secrets and revoke anything found.

For the rotation mechanics, see how to rotate API keys automatically; the same approach works for client secrets.

How does the client credentials flow work for AI agents and MCP?

Use client credentials when an AI agent acts on its own behalf, such as a scheduled reporting agent; use a user flow plus token exchange when it acts for a person. An agent using client credentials to do a user's bidding gets the client's full access instead of the user's, which breaks least privilege.

  • One client per agent, so each can be monitored, limited and revoked on its own.
  • Narrow scopes per tool, with write, export and delete behind separate scopes.
  • Short-lived tokens and, where possible, private_key_jwt or federation instead of a secret in the agent's environment.
  • Token exchange for delegation: when the agent acts for a user, exchange the user's token for one scoped to the API, recording both the user and the agent (RFC 8693).

The MCP authorization specification builds on OAuth, so the same rules apply to MCP servers: tokens must be issued for the specific server, and servers must reject tokens issued for anyone else. For setup, see securing MCP endpoints.

When should you use the client credentials flow?

Use the client credentials flow for any back-end workload that calls an API on its own behalf and can keep a credential secret. Don't use it for anything that runs on a user's device or acts for a specific person.

The client credentials flow is right for you if

  • A service, batch job, partner back end or agent calls an API with no user involved.
  • The client runs on infrastructure you or the partner control, not on a user's device.
  • The same permissions apply no matter which user, if any, triggered the work.
  • You want short-lived, scoped tokens instead of permanent API keys.

The client credentials flow is not right if

  • The client is a browser or mobile app: it can't keep a secret. Use authorization code with PKCE.
  • The call acts for a specific user: use the authorization code flow, or token exchange from the user's token.
  • You need the user's own permissions to apply: client credentials only carries the client's.

Where should client credentials tokens be enforced?

Validate client credentials tokens at the API gateway, so every API checks issuer, audience, expiry and scope the same way, and keep object-level checks in the service. Gateways also apply per-client rate limits, which matter more for machines than for people, because a misbehaving job can send thousands of calls a minute.

Large organisations often run several gateways, each with its own way of registering clients and validating tokens. The DigitalAPI API Gateway applies one token validation, scope and rate-limit policy for machine clients across the gateways you already run. Teams using the DigitalAPI API Developer Portal let partners register their own machine clients, upload public keys for private_key_jwt, and request only the scopes their plan allows.

See how DigitalAPI manages machine-to-machine access across every gateway you run → Book a Demo

What are the most common client credentials mistakes?

Most client credentials problems come from treating the client secret like a permanent API key: shared, never rotated, and able to do everything. These are the ones to check for:

Common client credentials mistakes and fixes

MistakeWhat happensFix
Requesting a new token for every API callSlow calls, overloaded authorization server, rate-limit errorsCache and reuse tokens until shortly before expiry
One client ID shared by many servicesCan't revoke one service; logs can't tell them apartOne client per workload
Secrets in code, config files or CI logsSecrets leak to repositories and logsSecrets manager, or private_key_jwt and federation
Secrets sent in query stringsSecrets stored in server and proxy logsAuthorization header or a signed assertion
Broad scopes such as * or adminA leaked secret can do everythingRegister narrow scopes per client
No audience or resourceTokens work on APIs they weren't meant forRequest one API per token and check aud
Using client credentials in a browser or mobile appAnyone can extract the secretAuthorization code with PKCE
Using client credentials to act for usersThe user's own permission limits are skippedAuthorization code or token exchange
Secrets that never rotateOld leaks stay exploitable for yearsRotate on a schedule with overlap

Swipe sideways to see all columns →

Key takeaways

  • The client credentials flow gets a token for a machine acting on its own behalf, with no user and no refresh token.
  • How the client authenticates matters most: prefer private_key_jwt, mTLS or workload identity federation over shared secrets.
  • Cache tokens and renew shortly before expiry; one request should serve many calls.
  • One client per workload, narrow scopes, one API per token, and short lifetimes.
  • Never use client credentials in browser or mobile apps, or to act for a user.

Frequently asked questions

1. What is the client credentials flow?

The client credentials flow is an OAuth 2.0 grant type that lets an application get an access token using its own credentials, with no user involved. The client authenticates to the authorization server's token endpoint, receives a short-lived token for the APIs it's registered to use, and sends it with each API call. It's defined in RFC 6749 section 4.4.

2. When should I use the client credentials flow?

Use the client credentials flow when a back-end service, batch job, partner server or AI agent calls an API on its own behalf and runs somewhere it can keep a credential secret. Don't use it in browser or mobile apps, or when the call should act with a specific user's permissions.

3. Does the client credentials flow return a refresh token?

No. RFC 6749 says a refresh token should not be issued for the client credentials grant, because the client can request a new access token at any time using its own credentials. Clients should cache the access token and request a new one shortly before it expires.

4. What is the difference between client credentials and authorization code?

The client credentials flow issues a token that represents the application itself, with no user involved. The authorization code flow issues a token for a user who signs in and consents, through a browser redirect. Use client credentials for machine-to-machine calls and authorization code with PKCE when a user is present.

5. What is machine-to-machine authentication?

Machine-to-machine (M2M) authentication is how software proves its identity to other software without a person involved, such as a service calling an API. Common methods are API keys, OAuth client credentials with a secret, signed JWT assertions or certificates, and workload identity federation, which uses a token from the platform instead of a stored secret.

6. What is private_key_jwt?

private_key_jwt is a client authentication method, defined in RFC 7523 and OpenID Connect, where the client signs a short-lived JWT with its private key and sends it to the token endpoint instead of a client secret. The authorization server verifies it with the client's registered public key. Nothing reusable is exposed if the request is intercepted.

7. How long should a client credentials access token last?

Most client credentials access tokens should last between 5 and 60 minutes. Shorter lifetimes limit the damage of a leaked token and make permission changes take effect sooner. Because the client can get a new token at any time, there's no need for long-lived access tokens.

8. How do I rotate a client secret without downtime?

Give the client a second active secret, deploy it to the workload, confirm all token requests use it, then revoke the old secret. Supporting two secrets per client at once makes zero-downtime rotation possible. Rotate on a schedule, such as every 90 days, and immediately after any suspected leak.

9. What is workload identity federation?

Workload identity federation lets a workload authenticate with a short-lived token its platform already issues, such as a Kubernetes service account token or a GitHub Actions OIDC token, instead of a stored client secret. The authorization server trusts the platform's issuer and exchanges that token for an access token, so there's no secret to store, leak or rotate.

10. Can AI agents use the client credentials flow?

Yes, when the agent acts on its own behalf, such as a scheduled reporting or monitoring agent. Give each agent its own client, narrow scopes and short-lived tokens. When an agent acts for a specific user, use the authorization code flow or token exchange instead, so the user's own permissions limit what the agent can do.

Conclusion

The client credentials flow is how most machines get into APIs: a service proves who it is, gets a short-lived token, and uses it until it expires. The flow itself is four steps. What decides whether it's safe is everything around it.

Authenticate clients with keys, certificates or federation instead of shared secrets where you can. Give every workload its own client and narrow scopes, cache tokens instead of requesting them per call, rotate whatever secrets remain, and keep client credentials out of browsers, phones and user-facing actions. For the wider picture of how tokens work, read our guide to token-based authentication and the ultimate guide to API access control.


How safely do you grant API access to partners and AI agents? Get your free readiness score: Check Your API Access Readiness

Prefer a walkthrough?
Book a Demo
About the author
Dhayalan Subramanian

Dhayalan Subramanian is Associate Director, Product Growth at DigitalAPI, where he leads go-to-market and product growth for the company’s multi-gateway API management platform. His work focuses on helping large enterprises and mid-market cloud companies consolidate APIs across AWS, Azure, Apigee, Kong, MuleSoft, and other gateways into a single control plane for governance, discovery, monetization, and agent consumption.

‍

Dhayalan brings 14+ years of experience across product strategy, enterprise architecture, and engineering leadership. Earlier in his career, he held senior roles at Encora (as Associate Architect and Technical Manager), Mindtree (Technology Lead), Tech Mahindra (Technical Lead), and Primus Analytics, where he designed integration frameworks and delivered enterprise-grade digital platforms for global customers.

‍

At DigitalAPI, he works directly with platform, integration, and developer experience leaders at Fortune 500 organizations to operationalize unified API catalogs, developer portals, and MCP-ready APIs. He writes regularly on API developer experience, API governance, and AI agent architectures.

Become AI-ready
Make every API agent-callable.
An 8-week pilot. We connect to your gateways, ship MCP-callable APIs, and onboard your first agent.
0 rip-and-replace
Same auth, same audit
Live in production in 8 weeks
Get started

One email a fortnight. Worth opening.

A short digest of what we're writing, what we're learning from customers, and the handful of links you'd actually want from us. No tracking pixels.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.