OAuth2 Token Generation (Client Credentials Flow)

Purpose

This document explains how to generate an OAuth2 access token using the Client Credentials grant type. This is commonly used for server-to-server (machine-to-machine) communication where no user interaction is required.

Required Information

Ensure you have the following values provided by your API or authorization provider:

Parameter Description
tokenUrl The token endpoint URL to request access tokens
clientId The client ID of your application
clientSecret The client secret of your application
scope Requested access scope or permission levels
subscriptionKey Key used for APIs protected by API gateways (e.g. Azure API Management)

Step 1: Request an Access Token

Send a POST request to the token endpoint with the required form data:

curl --request POST 'https://your-auth-server.com/oauth2/token' \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data-urlencode 'grant_type=client_credentials' \
  --data-urlencode 'client_id=YOUR_CLIENT_ID' \
  --data-urlencode 'client_secret=YOUR_CLIENT_SECRET' \
  --data-urlencode 'scope=YOUR_SCOPE'
  

Example Token Response

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600
}
  

Step 2: Use the Access Token in API Requests

Include the access_token in the Authorization header:

Authorization: Bearer YOUR_ACCESS_TOKEN
Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY
  

Example API Call using curl

curl --request GET 'https://api.yourservice.com/v1/data' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY'