Skip to main content

Client Credentials Flow

The Client Credentials Grant is a type of OAuth 2.0 flow that allows a client application to request access tokens directly from an authorization server by using its own credentials. This flow is specifically designed for Machine-to-Machine (M2M) authentication scenarios where no user interaction is required.

This flow is considered the best practice when requiring a Machine-To-Machine Authentication (secured backend communication). It is the better alternative to API-Keys, as access tokens are only temporarily valid and the access-token can be obtained for specific clients.

When to Use Client Credentials Flow

The Client Credentials Flow is ideal for:

  • Server-to-Server Communication: Backend services communicating with each other
  • Microservices Architecture: Services within a distributed system authenticating to each other
  • API-to-API Integration: Third-party services integrating with your APIs
  • Scheduled Jobs: Automated tasks that need to access protected resources
  • Background Services: Services that run without user interaction

Key Advantages

  • No User Interaction: Perfect for automated processes and backend services
  • Secure Credential Storage: client_secret can be stored securely on the server (never exposed to clients)
  • Temporary Tokens: Access tokens have expiration times, reducing risk if compromised
  • Scope-Based Access: Tokens can be scoped to specific permissions
  • Better than API Keys: Tokens are time-limited and can be revoked, unlike static API keys

How it Works

client-cred-flow

Before we step into how it works, let's understand some useful parameters.

Parameter NameDescription
client_idClient which represents the business-App in cidaas
client_secretSuitable client_secret (~ password) for the business-App. Must be kept secure on backend server only
grant_typeclient_credentials needs to be mentioned to use this grant type
scopeOptional parameter that restricts the permissions of your issued access token
access_tokenA string that represents the authorization granted to the client (application) to access protected resources on behalf of the client itself (not a user)

Step 1: The client application makes a POST request to the token endpoint containing client_id, client_secret, grant_type=client_credentials, and optionally scope.

Step 2: cidaas validates the credentials and responds with an access_token, token_type (typically "Bearer"), and expires_in (token expiration time in seconds).

Step 3: The client uses the access_token in the Authorization header to access protected resources on the resource server.

Step 4: The resource server validates the access_token using one of the following methods:

  • A: Token introspection: Make an introspection call to cidaas to validate the token's authenticity and obtain information about the token (scopes, expiration, client, etc.).
  • B: Offline validation: Validate the token's signature and check that the expiration time is in the future (for JWT tokens).

Step 5: If the token is valid, the resource server responds with the requested resource.

Security Note

Important: The client_secret must be kept secure and stored only on your backend server. Never expose it to client-side code or commit it to version control. This flow is designed for server-to-server communication where credentials can be securely stored.

M2M Security Best Practices

When implementing Client Credentials Flow for Machine-to-Machine communication, follow these security best practices:

1. Secure Credential Storage

  • Never commit secrets to version control: Use environment variables or secret management systems (e.g., AWS Secrets Manager, HashiCorp Vault, Azure Key Vault)
  • Use different credentials per environment: Separate client_id and client_secret for development, staging, and production
  • Rotate credentials regularly: Implement a credential rotation policy
  • Limit credential access: Only grant access to credentials to services that absolutely need them

2. Token Management

  • Use short-lived tokens: Set appropriate expiration times (typically 1 hour or less)
  • Cache tokens appropriately: Cache access tokens in memory to avoid frequent credential exchanges, but respect token expiration
  • Scope tokens appropriately: Request only the minimum scopes required for the operation
  • Monitor token usage: Log and monitor all token requests for anomalies
  • Note on refresh tokens: Client Credentials Flow typically does not use refresh tokens. Instead, request a new access token when the current one expires.

3. Network Security

  • Use HTTPS/TLS: Always use encrypted connections for all API calls
  • Implement IP whitelisting: Restrict token requests to known IP addresses when possible
  • Use mutual TLS (mTLS): For additional security in high-risk scenarios

4. Token Validation

  • Always validate tokens: Never trust tokens without validation
  • Use token introspection: For real-time validation, use the introspection endpoint
  • Implement caching: Cache validation results to reduce load, but respect token expiration
  • Check token revocation: Verify that tokens haven't been revoked

5. Error Handling and Logging

  • Log authentication failures: Monitor failed authentication attempts
  • Implement rate limiting: Prevent brute force attacks on credentials
  • Alert on anomalies: Set up alerts for unusual patterns (e.g., many failed attempts, requests from unknown IPs)
  • Audit token usage: Maintain audit logs of all token requests and usage

6. Scope and Permission Management

  • Principle of least privilege: Grant only the minimum permissions required
  • Use custom scopes: Define custom scopes for your specific use cases
  • Review scope assignments: Regularly review and audit scope assignments
  • Implement scope validation: Validate that tokens have required scopes before granting access

Video Tutorial

Let's look at a simple tutorial to get an idea of the Client Credentials Flow.

client-credential-flow

Technical Integration

APIDescriptionLink to API
Step 1: Generate TokenThis call is used to generate an access token based on the grant type passed. For Client Credentials Flow, use grant_type=client_credentialsView API
Step 4: Token IntrospectionValidate and get information about an access token. Use this to verify token validity, expiration, and scopesView API

Example Implementation

Here's a complete example of implementing Client Credentials Flow:

# Step 1: Request Access Token
curl --request POST \
--url 'https://{{base_url}}/token-srv/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id={{client_id}}' \
--data-urlencode 'client_secret={{client_secret}}' \
--data-urlencode 'scope={{desired_scopes}}'

# Response:
# {
# "access_token": "eyJhbGciOiJSUzI1NiIs...",
# "token_type": "Bearer",
# "expires_in": 3600,
# "scope": "api:read api:write"
# }

# Step 2: Use Access Token to Access Protected Resource
curl --request GET \
--url 'https://{{resource_server}}/api/protected-resource' \
--header 'Authorization: Bearer {{access_token}}'

# Step 4: Validate Token (Optional - using introspection)
curl --request POST \
--url 'https://{{base_url}}/token-srv/introspect' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Bearer {{access_token}}' \
--data-urlencode 'token={{access_token}}'

Comparison with Other Flows

AspectClient CredentialsAuthorization CodePKCE
User Interaction❌ No✅ Yes✅ Yes
Client Secret✅ Required✅ Required❌ Not required
Use CaseM2M, Backend ServicesWeb Apps with BackendSPAs, Mobile Apps
Token LifetimeConfigurableConfigurableConfigurable
Scope Support✅ Yes✅ Yes✅ Yes
Refresh Tokens❌ Not typically used✅ Yes✅ Yes
Best ForServer-to-server, APIsTraditional web appsPublic clients

Need Support?

Please contact us directly on our support page