JAVASCRIPT

Obtain OAuth 2.0 Client Credentials Token

Securely acquire an OAuth 2.0 access token using the client credentials flow, ideal for server-to-server API integrations without user interaction.

const fetch = require('node-fetch'); // Use for Node.js environments

async function getOAuthClientCredentialsToken(tokenUrl, clientId, clientSecret, scope = '') {
  try {
    const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
    const response = await fetch(tokenUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Basic ${credentials}`
      },
      body: new URLSearchParams({
        'grant_type': 'client_credentials',
        'scope': scope
      }).toString()
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`Failed to get OAuth token: ${response.status} - ${errorText}`);
    }

    const data = await response.json();
    return data.access_token; // Returns the access token
  } catch (error) {
    console.error('Error fetching OAuth token:', error);
    throw error;
  }
}

// Example usage:
// (async () => {
//   const TOKEN_URL = 'https://api.example.com/oauth/token';
//   const CLIENT_ID = process.env.OAUTH_CLIENT_ID;
//   const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET;
//   const SCOPE = 'read write';
//
//   try {
//     const accessToken = await getOAuthClientCredentialsToken(TOKEN_URL, CLIENT_ID, CLIENT_SECRET, SCOPE);
//     console.log('Access Token:', accessToken);
//     // You can now use this access token to make authorized API calls
//   } catch (err) {
//     console.error('Authentication failed:', err);
//   }
// })();
How it works: This Node.js snippet demonstrates how to obtain an OAuth 2.0 access token using the client credentials grant type. It constructs a POST request to the token endpoint, sending the client ID and client secret in the Authorization header as a Base64 encoded string, and specifies the `grant_type` and optional `scope` in the request body. Upon success, it returns the `access_token` from the API's response. This flow is suited for server-to-server communication where no user interaction is involved.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs