Security

Client Credentials Flow Explained: OAuth 2.0 Machine-to-Machine

The client credentials flow is the OAuth 2.0 grant where an application gets an access token by authenticating as itself, with its own client ID and secret, and no user is involved. It is used for server-to-server calls such as background jobs, daemons and service accounts.

RFC 6749 section 4.4 describes it as a client requesting "access to the protected resources under its control". There is no consent screen, no redirect and no browser. The client makes one HTTPS request to the authorization server's token endpoint and gets a token back. For the general picture of how OAuth works, start with OAuth explained; this article covers only this one grant.

When to use the client credentials flow

Use it when the caller is a program acting for itself, not for a person. Typical cases:

  • A nightly job that reads data from an internal API.
  • One backend service calling another backend service.
  • A daemon or script that syncs data using the identity of the application. Microsoft's documentation calls these "daemons" or "service accounts".

Do not use it when the action must be done as a particular user, for example "read this user's calendar". That needs the authorization code flow, because the token has to represent the user's consent. The flow also has a hard restriction: RFC 6749 says "The client credentials grant type MUST only be used by confidential clients." A confidential client is one that can keep its credentials secret, such as code running on a server you control. Never put these credentials in a single-page app, a mobile app or any widely distributed program.

How the client credentials flow works

  1. Registration. You register the application with the authorization server and receive a client ID plus a credential, usually a client secret. The administrator or API owner grants the application the permissions it needs.
  2. Token request. The client sends an HTTPS POST to the token endpoint with grant_type=client_credentials, optionally a scope, and its client authentication.
  3. Token response. The authorization server checks the credentials and returns an access token with a lifetime.
  4. API call. The client sends the token to the resource server, normally in an Authorization: Bearer header.
  5. Renewal. When the token expires, the client repeats step 2.

Step 5 is the part that differs from other flows. RFC 6749 says "A refresh token SHOULD NOT be included" in the response. Microsoft's documentation says refresh tokens are never granted with this flow, because the client can use its own credentials to get a new access token whenever it needs one.

The token request

RFC 6749 defines two request parameters. grant_type must be set to client_credentials. scope is optional. The client must also authenticate. Section 2.3 of the RFC says the client and authorization server agree on an authentication method, and that the client must not use more than one method in each request. The usual choices are HTTP Basic authentication with the client ID and secret (defined in section 2.3.1), or sending the credentials in the request body.

Here is the request as Microsoft documents it for the Microsoft identity platform, with placeholders in place of real values:

POST /{tenant}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com:443
Content-Type: application/x-www-form-urlencoded

client_id={application-client-id}
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret={client-secret}
&grant_type=client_credentials

The same request as a curl command, taken from the same page:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \
  -d 'client_id={application-client-id}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret={client-secret}&grant_type=client_credentials' \
  'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token'

Replace {tenant} with your directory tenant. Microsoft notes that the client secret must be URL-encoded before it is sent, and that sending the credentials in the Authorization header as Basic authentication is also supported.

Other providers use the same shape with a different token URL. The token endpoint address is published in the provider's documentation; do not guess it.

The token response

A successful response is JSON. This is the format Microsoft documents (example output, token shortened):

{
  "token_type": "Bearer",
  "expires_in": 3599,
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6..."
}

expires_in is the token's lifetime in seconds, so 3599 is just under one hour. Cache the token and reuse it until shortly before it expires, instead of requesting a new one for every API call. Then send it to the API:

GET /v1.0/users HTTP/1.1
Host: graph.microsoft.com:443
Authorization: Bearer {access-token}

Microsoft also warns against reading tokens for APIs you do not own: tokens for Microsoft services can use a special format that does not validate as a JWT, so treat the token as an opaque string unless you own the API.

Scopes and permissions without a user

With no user, there is nobody to approve permissions on a consent screen. Permissions are granted to the application ahead of time. In Microsoft Entra, these are called application permissions (app roles), assigned by an administrator or the API's owner, and delegated permissions cannot be used because there is no user to act for. That is why the scope in the example above is https://graph.microsoft.com/.default: it tells the platform to issue a token containing whichever application permissions are already configured for that resource. Microsoft also says all scopes in one request must belong to a single resource, and that mixing resources returns an error.

Other providers handle this differently. Some let you request named scopes in the token request, others fix the permissions at registration. Check the provider's documentation, and request the smallest set of permissions the job needs.

Errors

A failed request returns HTTP 400 with a JSON body. Microsoft's documented example of an invalid scope looks like this (example output, shortened):

{
  "error": "invalid_scope",
  "error_description": "AADSTS70011: The provided value for the input parameter 'scope' is not valid. ...",
  "error_codes": [70011]
}

The error field is a code you can handle in software, and error_description is meant for people. Log both, along with any trace or correlation ID the response includes, but never log the client secret or the access token.

Keeping the credentials safe

The client secret is the whole identity of the application. Anyone who has it can request tokens and act as the application, and nothing in the flow asks a person to confirm. Microsoft's guidance is blunt: never publish the credential in source code, embed it in web pages, or use it in a widely distributed native application.

  • Store it outside the code. Use environment variables or a secrets manager. Do not commit it to a repository.
  • Prefer stronger credentials where offered. Microsoft says its platform also lets the calling service authenticate with a certificate or a federated credential instead of a shared secret, for a higher level of assurance. Both replace client_secret with a signed client_assertion in the request.
  • Rotate and revoke. If a secret may have leaked, create a new one, deploy it, and delete the old one. The steps in what to do when an API key leaks apply to client secrets as well.
  • Keep tokens short-lived and over HTTPS only. A bearer token works for whoever holds it until it expires.
  • Validate on the API side. If you own the resource server, check the token's issuer and the caller's identity before granting access. Microsoft specifically says to validate the issuer, not only the application ID, when using an access control list.

Client credentials flow compared with an API key

Both identify an application rather than a person, so they are easy to confuse. The difference is what travels with each request. An API key is sent to the API on every call. In the client credentials flow, the secret goes only to the authorization server, and the API receives a token that expires. The token can also be limited to specific permissions, and the authorization server can enforce rules before issuing it. For a longer comparison, see API key vs OAuth.

If you only need to understand what a stored client secret looks like or build a random one for a test environment, the password generator runs in your browser. Use real secrets from the provider's registration page for production, though, since the provider issues the credential.

If the token request fails

  • invalid_scope: the scope is wrong for that provider, or it mixes resources. On Microsoft, use the resource identifier plus /.default.
  • A 400 or 401 about the client: check the client ID, that the secret has not expired, and that you used only one authentication method in the request.
  • The token is issued but the API rejects it: the application probably has not been granted any permissions for that API, or an administrator has not approved them.

Frequently asked questions

Does the client credentials flow return a refresh token?
No. RFC 6749 says a refresh token SHOULD NOT be included in the response, and Microsoft's documentation says refresh tokens are never granted with this flow. The client already holds its own credentials, so when the access token expires it simply makes the same token request again.
Can a browser or mobile app use the client credentials flow?
It should not. RFC 6749 says the grant MUST only be used by confidential clients, meaning clients that can keep a secret. Code that ships to users' devices or runs in a web page cannot hide a secret, so anyone could extract it and request tokens as that application.
Is the client credentials flow the same as using an API key?
They are similar in that one secret identifies one application. The difference is that the client credentials flow exchanges the secret at the authorization server for a short-lived access token, so the secret itself is not sent to the API on every call, and the token carries only the permissions granted to the application.
What is the scope parameter for in this flow?
It is optional in RFC 6749 and names the access the client is asking for. Providers define its values. On the Microsoft identity platform it is required and must be the resource's identifier followed by /.default, such as https://graph.microsoft.com/.default, which requests the application permissions already configured for the app.

Sources