JAVASCRIPT

Securely Authenticate API Requests with OAuth 2.0 Client Credentials Flow

Demonstrate how to implement the OAuth 2.0 Client Credentials flow in Node.js for secure server-to-server API authentication, obtaining and using an access token.

const axios = require('axios');

// Configuration for your OAuth client
const TOKEN_URL = 'https://your-auth-server.com/oauth/token';
const API_URL = 'https://your-resource-server.com/api/data';
const CLIENT_ID = process.env.OAUTH_CLIENT_ID;
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET;
const SCOPES = 'read:data write:data'; // Request necessary scopes

async function getAccessToken() {
  try {
    const response = await axios.post(
      TOKEN_URL,
      new URLSearchParams({
        grant_type: 'client_credentials',
        scope: SCOPES,
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
      }).toString(),
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    );
    return response.data.access_token;
  } catch (error) {
    console.error('Error fetching access token:', error.response ? error.response.data : error.message);
    throw new Error('Failed to obtain access token.');
  }
}

async function fetchDataWithAccessToken(accessToken) {
  try {
    const response = await axios.get(API_URL, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  } catch (error) {
    console.error('Error fetching data:', error.response ? error.response.data : error.message);
    throw new Error('Failed to fetch data with access token.');
  }
}

// Example usage
(async () => {
  if (!CLIENT_ID || !CLIENT_SECRET) {
    console.error('OAUTH_CLIENT_ID and OAUTH_CLIENT_SECRET environment variables must be set.');
    return;
  }
  try {
    const accessToken = await getAccessToken();
    console.log('Access Token obtained:', accessToken.substring(0, 10) + '...'); // Log first 10 chars
    const apiData = await fetchDataWithAccessToken(accessToken);
    console.log('API Data:', apiData);
  } catch (error) {
    console.error('Integration failed:', error.message);
  }
})();
How it works: This Node.js snippet demonstrates the OAuth 2.0 Client Credentials flow, used for server-to-server authentication without user involvement. It first requests an access token from an authorization server using the `client_id` and `client_secret`. Once the token is obtained, it's included in the `Authorization` header as a Bearer token for subsequent requests to a protected resource API, ensuring secure communication between services.

Need help integrating this into your project?

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

Hire DigitalCodeLabs