Client Credentials Guide

Machine-to-machine access with OAuth 2.0: getting a token, authenticating the client, and validating the token at your API

The client credentials grant lets a program (a batch job, a backend service, a pipeline) get an access token for an API as itself, with no person signing in. This guide explains the standard, how to choose a way for the client to prove who it is, and how the API should check what it receives. The sections follow the RFCs listed at the end; everything specific to this particular service is collected in one box after the troubleshooting table, so you can tell the standard from the product.

1. How the flow works

RFC 6749 section 4.4 defines the grant. The client sends one request to the authorization server's token endpoint, proves its identity, and receives an access token. There is no redirect, no user, and no consent screen. The client then calls the API with the token, and the API decides whether to honour it.

Client credentials sequence The client sends a token request with its credentials to the authorization server and receives an access token. It calls the API with the token. The API may ask the authorization server to introspect the token, then answers the client with success, 401 or 403. Client Authorization server API 1. Token request: credentials, resource, scope 2. Access token and expires_in 3. Request with Authorization: Bearer token 4. Optional: introspection 5. Success, or 401 / 403
Step 4 is optional and appears again under "JWT or opaque tokens, and introspection".

The token request

POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&resource=https%3A%2F%2Fapi.example.com%2Forders
&scope=Orders.Read
&client_id=billing-batch
&client_secret=<the client's secret>
  • grant_type must be client_credentials. The body is form-encoded, never JSON.
  • resource (RFC 8707) names the API the token is for. The server should restrict the token's audience to it, so a token for one API is useless at another.
  • scope (RFC 6749 section 3.3) is a space-delimited list of the permissions you want. Ask only for what the call needs. If you omit it, the server applies its own default, which may be everything you are allowed.
  • The client's credentials go in the same request. See the next section for the options.

The response

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

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6ImF0K2p3dCIsImtpZCI6IjEifQ...",
  "token_type": "Bearer",
  "expires_in": 900,
  "scope": "Orders.Read"
}
  • The response is never cacheable (Cache-Control: no-store), but you should keep the token in memory and reuse it until shortly before expires_in runs out. Asking for a new token on every API call is slow and invites rate limits.
  • The grant is for a client acting as itself, so there is no end user to come back to. RFC 6749 section 4.4.3 says a refresh token SHOULD NOT be included. When the token expires, authenticate again.
  • There is no ID token either: nobody signed in.

2. Choosing client authentication

Whoever holds the client's credential is the client, so this choice sets how much damage a leak can do. The token endpoint accepts a client's proof in one of these ways. A server usually lets each client use exactly one.

Client authentication methods and their trade-offs
Method What proves identity Strengths Weaknesses
client_secret_basic / client_secret_post A shared secret. RFC 6749 section 2.3.1 prefers HTTP Basic and says credentials in the request body are NOT RECOMMENDED, though a server may allow them. Simple. Works everywhere. Both sides know the secret. It leaks through logs, tickets, repositories and backups. It needs rotation and an expiry.
private_key_jwt A short-lived JWT the client signs with its private key (RFC 7523, OpenID Connect Core section 9). The server holds only the public key. The private key never leaves the client. Assertions expire in minutes. Rotation is publishing a second public key. The client must manage a key pair and sign assertions. Clock skew matters.
tls_client_auth / self_signed_tls_client_auth A client TLS certificate (RFC 8705, mTLS). Strong proof at the transport. The same certificate can bind the token. Needs a TLS terminator that passes the client certificate through, and certificate lifecycle management.
Workload identity A token the platform issues to the workload (a Kubernetes service account, a cloud IAM role, a CI provider) is exchanged for an access token, usually with a signed assertion as in RFC 7523. No long-lived secret to store at all. Needs trust set up between the platform and the server, and the server must support it.

Rule of thumb: use a secret for low-risk integrations you can rotate easily, and a key pair (or workload identity) for anything that touches sensitive data. Prefer a method where the credential is never sent to the server in a reusable form.

A signed assertion

POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&resource=https%3A%2F%2Fapi.example.com%2Forders
&client_id=billing-batch
&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion=<signed JWT>

RFC 7523 section 3 requires iss, sub, aud and exp in the assertion:

  • iss and sub: both the client's client_id.
  • aud: the authorization server's issuer identifier or token endpoint URL, so an assertion cannot be replayed to a different server.
  • exp: a few minutes ahead at most.
  • jti: a unique value. RFC 7523 makes it optional, but OpenID Connect Core requires it for private_key_jwt, and servers use it to refuse an assertion they have already seen.

3. Validating tokens at your API

An API that accepts a token must decide for itself whether to trust it. Most servers issue JWT access tokens in the format of RFC 9068, which you can check offline. Do every step; skipping one is how confused-deputy and token-substitution bugs happen.

  1. Signature. Fetch the server's key set from its jwks_uri (RFC 8414 metadata) and pick the key by kid. Fix the algorithm you accept (for example RS256) instead of trusting the token's alg header. Reject none and any HMAC algorithm when the key is a public key. Cache the key set for a short time and, on an unknown kid, refetch once (rate-limited) to pick up a rotation.
  2. Type. The header typ must be at+jwt (RFC 9068 section 4; application/at+jwt is also valid). This stops an ID token or another JWT being used as an access token.
  3. Issuer. iss must equal the issuer you trust, character for character.
  4. Audience. aud must contain your API's own identifier. A valid token issued for a different API must be refused.
  5. Expiry. exp must be in the future (and nbf, if present, in the past), allowing about a minute of clock skew.
  6. Permission. Only now check what the caller may do. The scope claim is a space-delimited list; the permission this operation needs must be an exact member. No case folding, no prefix matching, and no implication ("write" does not include "read").
# Python with PyJWT: validate, then authorize
import jwt


class Unauthorized(Exception):
    """Answer 401 with: WWW-Authenticate: Bearer error="invalid_token"."""


class Forbidden(Exception):
    """Answer 403 with: WWW-Authenticate: Bearer error="insufficient_scope"."""


jwks = jwt.PyJWKClient("https://auth.example.com/jwks")  # caches keys, refetches on an unknown kid


def authorize(token: str, needed: str) -> dict:
    try:
        header = jwt.get_unverified_header(token)
        if str(header.get("typ", "")).lower() not in ("at+jwt", "application/at+jwt"):
            raise Unauthorized("not an access token")
        key = jwks.get_signing_key_from_jwt(token).key
        claims = jwt.decode(
            token, key, algorithms=["RS256"],                     # fix the algorithm; never trust the header
            audience="https://api.example.com/orders",            # your API's own identifier
            issuer="https://auth.example.com",
            options={"require": ["exp", "iss", "aud", "sub"]},
            leeway=60,
        )
    except jwt.PyJWTError as error:                               # bad signature, expired, wrong aud/iss, unknown kid
        raise Unauthorized("invalid token") from error
    if needed not in claims.get("scope", "").split():             # exact match, no implication
        raise Forbidden("insufficient_scope")
    return claims

401 or 403?

  • 401 Unauthorized: the token is missing or fails any check above. Send WWW-Authenticate: Bearer error="invalid_token" (RFC 6750 section 3). The caller should get a new token, or give up.
  • 403 Forbidden: the token is valid but lacks the permission. Send WWW-Authenticate: Bearer error="insufficient_scope", scope="Orders.Write" (RFC 6750 section 3.1). Retrying with a new token will not help; the client needs a grant.
  • Never use sub as a person. In a client credentials token it identifies the client.

4. JWT or opaque tokens, and introspection

A JWT (RFC 7519) carries its own claims and signature, so an API can check it without calling anyone. That is fast and keeps the API working if the authorization server is briefly down. The cost is that a JWT cannot be revoked before it expires: if you disable a client or remove a permission, tokens already issued keep validating offline until exp. Short lifetimes bound that revocation window.

An opaque token is just a reference the API must look up. Introspection (RFC 7662) gives that lookup for any token: the API POSTs the token to the server's introspection endpoint and gets {"active": true, ...} or {"active": false}. The endpoint itself must be protected, and an inactive answer should reveal nothing else about the token.

Offline validation compared with introspection
  Offline JWT validation Introspection
Revocation seenAt expiryImmediately
Cost per callLocal CPUA network round trip
If the server is downKeeps workingMust fail closed or use a cache
Extra credential for the APINoneYes

A common pattern: validate offline for every call, and introspect for the sensitive ones (deleting data, moving money), where an immediate revocation matters.

5. Sender-constrained tokens

A bearer token works for whoever presents it (RFC 6750 section 5). If it leaks from a log or a proxy, the thief is the client until it expires. A sender-constrained token is tied to a key the client holds, so a copy is useless without that key.

  • mTLS (RFC 8705). The token carries a cnf claim with the thumbprint of the client's TLS certificate (x5t#S256). The API checks that the certificate on the TLS connection matches. It is strong, but every hop between client and API must preserve the client certificate.
  • DPoP (RFC 9449). The client signs a small proof JWT (typ dpop+jwt, its public key in the header, htm, htu, iat, jti) for the token request, and the token carries cnf.jkt, the thumbprint of that key. On each API call the client sends Authorization: DPoP <token> and a fresh proof that also includes ath, a hash of the token. The API checks the signature, method, URL, freshness, that the jti was not used before, and that the key matches cnf.jkt. It works at the application layer, with no change to TLS.

Whichever you use, a constrained token must be refused when presented as a plain bearer token, or the protection is gone. An API that does not understand the scheme must reject the token rather than ignore the constraint.

6. Scopes and permission naming

A scope is just a case-sensitive string (RFC 6749 section 3.3). What it means is decided by the API's owner, because only the owner knows what the API does. Choose names that stay true:

  • Name a permission by what it protects and what it allows, such as Orders.Read or Orders.Write.
  • Keep verbs independent. Write does not include Read, and an administrative verb does not include the others. Grant what is needed, and nothing implied.
  • Use stable names. Renaming a permission silently changes what existing grants mean.
  • Bind the permission to one API by audience, not by clever scope names: the same Orders.Read on two APIs must not be interchangeable, which is what the resource parameter and aud are for.
  • Request narrowly, and cache a token per set of permissions rather than asking for everything once.

7. Operating it safely

A service identity has no person to notice that it is wrong, so most failures are slow drift. A short list that prevents the common ones:

  • One owner, one application, one environment per client. Never share a client between applications or between production and test.
  • Grant the minimum and record why. Review grants regularly and remove any that are unused.
  • Prefer key pairs for sensitive data, and give secrets an expiry. Rotate with an overlap so callers can switch without downtime.
  • Keep tokens short-lived and cache them in memory. Never log a token, secret or assertion, and never put one in a URL.
  • Store credentials in a secret manager, not in source control or images.
  • Watch for failures. A spike of failed token requests or denied calls is the earliest sign of a leaked or misused credential.

8. Troubleshooting

Common errors, their usual cause and the fix
Where Error Usual cause What to do
Token endpointinvalid_requestA required parameter is missing or repeated, or the body is JSON instead of form-encoded.Send application/x-www-form-urlencoded and check each parameter.
Token endpointinvalid_clientWrong or expired secret, a signature the server cannot verify, a wrong aud or reused jti in the assertion, or the wrong authentication method for this client. Servers deliberately give the same answer for each.Check the credential and the method the client is registered for, the assertion's aud, and your clock.
Token endpointunauthorized_clientThe client is authenticated but not allowed this grant type, or has been deactivated.Ask the administrator to enable client credentials for the client.
Token endpointinvalid_targetThe resource is missing, unknown, repeated, or the client has no access to it. Servers do not say which, so a client cannot discover other APIs.Send exactly one exact API identifier the client has been granted.
Token endpointinvalid_scopeA requested permission is unknown, malformed, or not granted to this client.Request only granted permissions, spelled exactly.
Token endpointinvalid_dpop_proofThe DPoP proof has the wrong method or URL, is stale (clock skew), reuses a jti, or is signed with an unsupported algorithm.Build a new proof per request with a fresh jti and iat.
Token endpoint429Too many token requests, usually from minting a token per call.Cache the token until just before expiry and honour Retry-After.
API401 invalid_tokenExpired token, wrong audience, wrong issuer, typ not at+jwt, unknown kid, or a clock that is minutes off.Decode the token (never paste a live one into a website) and compare each claim with the checklist. Fetch a new token.
API403 insufficient_scopeThe token is valid but the permission is not in scope.Ask for the permission, and have it granted to the client first.
APIWorked, then stoppedThe token expired, a grant was revoked or removed, or the secret expired.Renew near expiry. If new tokens are refused, the cause is on the authorization server.

What authserver.app supports today

Everything above is the standard. Everything below is how this service implements it, checked against the running code. If a feature is not listed as supported, do not build against it.

Set-up

  • Each tenant has its own issuer, https://<tenant host>/oauth2. It is off until a tenant administrator turns on Service access (OIDC Apps, then Service access). Everything in this box is reached from there, with the access_management grant.
  • Register the API (its identifier, such as api://claims-api, and its permissions), register the client as an OIDC App with the client credentials grant, then grant the client each permission with a recorded reason. A grant only works when the client's environment matches the API's, and a permission marked high-tier can only be granted to a private_key_jwt client.
  • Discovery (RFC 8414): /oauth2/.well-known/oauth-authorization-server (also served at /.well-known/oauth-authorization-server/oauth2). Keys: /oauth2/.well-known/jwks, cacheable for 60 seconds; an unknown kid after a key rotation is the cue to refetch.

Token request

POST /oauth2/token HTTP/1.1
Host: acme.authserver.app
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&resource=api://claims-api
&scope=Claims.Read
&client_id=claims-batch
&client_secret=<secret>
HTTP/1.1 200 OK
Cache-Control: no-store
Pragma: no-cache

{"access_token": "eyJ...", "token_type": "Bearer", "expires_in": 3600, "scope": "Claims.Read"}
HTTP/1.1 400 Bad Request

{"error": "invalid_client", "error_description": "Client authentication failed"}
HTTP/1.1 400 Bad Request

{"error": "invalid_target", "error_description": "The requested resource is invalid, unknown, or not granted to this client"}
HTTP/1.1 400 Bad Request

{"error": "invalid_scope", "error_description": "The requested scope is not granted"}
  • Client authentication: client_secret_post and private_key_jwt only, one per client. An assertion is signed with RS256 or ES256, its aud is the issuer or the token URL, and each jti is accepted once.
  • Resource: send exactly one resource. If scope is left out, the token carries every permission the client holds on that API; ask narrowly anyway.
  • Errors: a JSON body, normally with HTTP 400. An unknown client, a wrong secret and an expired secret all give the same invalid_client; a missing, unknown or ungranted API gives the same invalid_target.
  • Limits: the token endpoint is rate limited per IP address and per client; a limited request is answered 429, and the per-client limit adds Retry-After.
  • Older endpoint: the per-app endpoint /oidc/<n>/token still accepts client credentials for existing clients, but is deprecated. Use the tenant endpoint.

The token

A decoded token, from a real request for Claims.Read (the signature is not shown):

{
  "header": {"alg": "RS256", "typ": "at+jwt", "kid": "bY09nZ3akZ6u2NGljBsHliPXWRSkk4AkLr6WOodTrdE"},
  "claims": {
    "iss": "https://acme.authserver.app/oauth2",
    "sub": "client:claims-batch",
    "aud": "api://claims-api",
    "client_id": "claims-batch",
    "scope": "Claims.Read",
    "gty": "client_credentials",
    "exp": 1793291130,
    "iat": 1793287530,
    "jti": "5f302529-241a-4242-a115-cfc232f18947"
  }
}
  • A JWT signed with RS256, header typ at+jwt, in the RFC 9068 shape: iss (the issuer), sub (client:<client_id>), aud (the API identifier), client_id, scope, gty (client_credentials), exp, iat and jti. scope never contains openid.
  • Lifetime: the smallest of the client's access-token lifetime (a new service client starts with the tenant default, 900 seconds unless the administrator changed it; clients created earlier carry 3600 seconds), the API's own ceiling if one is set, and the tenant maximum (at most 3600 seconds), never under 60 seconds. Ask your administrator to lower them.
  • A refresh token is not issued, and no ID token is issued.

Discovery and keys

GET /oauth2/.well-known/oauth-authorization-server

{
  "issuer": "https://acme.authserver.app/oauth2",
  "jwks_uri": "https://acme.authserver.app/oauth2/.well-known/jwks",
  "response_types_supported": [],
  "token_endpoint": "https://acme.authserver.app/oauth2/token",
  "grant_types_supported": ["client_credentials"],
  "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt"],
  "token_endpoint_auth_signing_alg_values_supported": ["RS256", "ES256"],
  "dpop_signing_alg_values_supported": ["ES256", "RS256"],
  "introspection_endpoint": "https://acme.authserver.app/oauth2/introspect",
  "introspection_endpoint_auth_methods_supported": ["bearer"]
}
GET /oauth2/.well-known/jwks

{"keys": [{"kty": "RSA", "use": "sig", "alg": "RS256", "kid": "bY09nZ3akZ6u2NGljBsHliPXWRSkk4AkLr6WOodTrdE", "n": "xYxc5oT68dAZ...", "e": "AQAB"}]}

response_types_supported is empty because this issuer has no authorization endpoint. Only the token and introspection endpoints are advertised.

Permissions

  • Named Resource.Verb with a verb of Read, Write, Delete or Admin. Each is independent: Write does not include Read, and Admin does not include the others. Match them exactly.
  • A client is only issued permissions it still holds. Revoking a grant, or deactivating the client or API, stops new tokens at once.

Introspection

POST /oauth2/introspect HTTP/1.1
Authorization: Bearer sra_<credential>
Content-Type: application/x-www-form-urlencoded

token=<access token>

HTTP/1.1 200 OK

{"active": true, "scope": "Claims.Read", "client_id": "claims-batch", "token_type": "Bearer",
 "exp": 1790000000, "iat": 1789996400, "sub": "client:claims-batch",
 "aud": "api://claims-api", "iss": "https://acme.authserver.app/oauth2", "jti": "...", "gty": "client_credentials"}
  • Each API gets its own credential on its Service access page: a secret starting sra_, shown once, with up to two active so one can be rotated in. A credential only answers for tokens issued for its own API; any other token is {"active": false}, as is one that has expired or been revoked. The answer is live, and scope shows only the permissions still granted.

Sender-constrained tokens

  • DPoP is available per client (turn on Require DPoP on the client). Send the proof in a DPoP header with ES256 or RS256 (RSA keys of 2048 bits or more), for POST to the token URL, with iat within 60 seconds and a jti used once. The token is then token_type DPoP with cnf.jkt, and the API must be called with Authorization: DPoP. Introspection reports cnf too. Server-provided nonces are not supported.

As an administrator sees it

  • Service access lists the APIs you protect: identifier, owner, environment, data tier and how many permissions each has.
  • An API's page shows its permissions, the grants on it (client, permission, reason, who granted it, expiry, with a Revoke button) and its introspection credentials.
  • A client's access page lists the grants it holds. The issuer page shows the issuer, key set and metadata URLs and the signing keys.

Operating it

  • Every token request, denial, grant and credential change is written to the security log with identifiers only. Secrets, assertions and tokens are never logged.
  • An API's owner has a read-only access report listing the clients that hold permissions on it, with the reason, who granted it and when it was last used.

Governance

  • It is off by default. A user with Access Management turns it on under Access Management, then Governance. Turning it on sets an enforcement date 30 days ahead; until then every finding is a warning and nothing is denied.
  • While it is on, a new service client needs a named owner and a purpose. Its tier is the highest data tier among its grants and cannot be set by hand. Existing clients get a profile marked "needs review".
  • By default a client secret expires: 365 days for a low-tier client and 180 days for a medium-tier one (a high-tier client should use a key). An expired secret is refused with the same invalid_client answer as a wrong one, but only from the enforcement date, and a secret that already exists lives at least one full lifetime past that date. A private_key_jwt client has no secret to expire.
  • Rotating a secret starts a new lifetime and keeps the old secret working for 24 hours, so callers can switch without downtime. A tenant can set the overlap from 1 to 168 hours.
  • By default reviews fall due every 90, 180 and 365 days for high, medium and low tiers. A user with Access Management records a review from the client's page, which also sets what the client is for and schedules the next review from its tier. The inventory flags orphaned clients (no active owner), overdue reviews, clients with no token for 90 days, grants unused for 90 days, and credentials that expire within 30 days or already have. It exports as a CSV of identifiers only.
  • A user with Access Management can change the secret lifetimes, review cycles, rotation overlap, unused window and expiry warning window under Governance, each within fixed limits, and can reassign a client's owner. Changes apply to the next rotation, review or report; nothing already issued is shortened.

Not supported

Not supported: client_secret_basic, mTLS (for client authentication or for certificate-bound tokens), workload identity federation, token exchange, DPoP nonces, access-request approval workflows, and periodic attestation campaigns. A refresh token is not issued.

References

  • RFC 6749: The OAuth 2.0 Authorization Framework (section 4.4, client credentials; section 2.3, client authentication; section 3.3, scope)
  • RFC 6750: Bearer Token Usage (the 401 and 403 responses)
  • RFC 7519: JSON Web Token (JWT)
  • RFC 7523: JWT Profile for OAuth 2.0 Client Authentication and Authorization Grants
  • RFC 7662: OAuth 2.0 Token Introspection
  • RFC 8414: OAuth 2.0 Authorization Server Metadata
  • RFC 8705: OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens
  • RFC 8707: Resource Indicators for OAuth 2.0
  • RFC 9068: JSON Web Token (JWT) Profile for OAuth 2.0 Access Tokens
  • RFC 9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP)