JAVASCRIPT

OAuth 2.0 Client Credentials Flow for Server API Access

Implement the OAuth 2.0 Client Credentials Grant in Node.js to securely obtain an access token for server-to-server API communication without any user interaction.

const axios = require('axios');
// require('dotenv').config(); // Uncomment if using .env file

const OAUTH_TOKEN_URL = 'https://api.example.com/oauth/token'; // Your OAuth provider's token endpoint
const CLIENT_ID = process.env.OAUTH_CLIENT_ID || 'your_client_id';
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || 'your_client_secret'; // Keep this secret!
const SCOPE = 'read write'; // Optional: specify required scopes

/**
 * Fetches an OAuth 2.0 access token using the Client Credentials Flow.
 * @returns {Promise<string>} A promise that resolves with the access token.
 */
async function getClientCredentialsAccessToken() {
  try {
    const response = await axios.post(OAUTH_TOKEN_URL, new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: SCOPE,
    }).toString(), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        // Basic Authorization header can also be used:
        // 'Authorization': `Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`,
      },
    });

    const accessToken = response.data.access_token;
    if (!accessToken) {
      throw new Error('Access token not found in response.');
    }
    console.log('Successfully obtained access token (first 10 chars):', accessToken.substring(0, 10) + '...');
    return accessToken;
  } catch (error) {
    console.error('Error obtaining OAuth token:', error.response ? error.response.data : error.message);
    throw new Error('Failed to get access token using client credentials.');
  }
}

// Example usage: Fetching a token and then using it for an API call
(async () => {
  try {
    const accessToken = await getClientCredentialsAccessToken();
    
    // Now use this accessToken to make authenticated API calls
    const protectedResourceUrl = 'https://api.example.com/protected/data';
    const apiResponse = await axios.get(protectedResourceUrl, {
      headers: {
        'Authorization': `Bearer ${accessToken}`,
      },
    });

    console.log('Protected API Data:', apiResponse.data);

  } catch (error) {
    console.error('Failed to perform API integration with OAuth:', error.message);
  }
})();
How it works: This Node.js snippet demonstrates the OAuth 2.0 Client Credentials Grant flow, a common method for server-to-server API authentication. This flow allows an application (acting as a client) to obtain an access token directly from an authorization server using its own client ID and client secret, without involving an end-user. It's ideal for machine-to-machine communication where your backend service needs to access another API on its own behalf. The generated access token is then used in the Authorization header for subsequent requests to protected API resources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs