JAVASCRIPT

Obtaining OAuth2 Client Credentials Token for Server-to-Server API Access

Securely obtain an OAuth 2.0 access token using the client credentials flow for server-to-server API integrations, demonstrating a common authentication pattern for backend services.

const fetch = require('node-fetch'); // In Node.js, install node-fetch for fetch API

const OAUTH_TOKEN_URL = 'https://your-oauth-server.com/token';
const CLIENT_ID = 'your-client-id';
const CLIENT_SECRET = 'your-client-secret';
const SCOPE = 'api.read api.write'; // Optional: scope for the token

async function getClientCredentialsToken() {
  try {
    const authString = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');

    const response = await fetch(OAUTH_TOKEN_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Basic ${authString}`
      },
      body: new URLSearchParams({
        'grant_type': 'client_credentials',
        'scope': SCOPE
      }).toString()
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`Failed to get OAuth token: ${response.status} ${response.statusText} - ${JSON.stringify(errorData)}`);
    }

    const data = await response.json();
    console.log('Access Token:', data.access_token);
    console.log('Expires In:', data.expires_in);
    return data.access_token;
  } catch (error) {
    console.error('Error fetching OAuth token:', error);
    throw error;
  }
}

// Example usage:
// getClientCredentialsToken().then(token => {
//   console.log('Token successfully retrieved:', token);
// }).catch(err => {
//   console.error('Failed to get token in main call:', err);
// });
How it works: This snippet demonstrates how a backend application can obtain an OAuth 2.0 access token using the client credentials grant type. This flow is ideal for server-to-server communication where there is no user involvement. It sends the client ID and secret, base64-encoded in the Authorization header, along with `grant_type=client_credentials` in the request body to the OAuth token endpoint. Upon success, it receives an access token that can then be used to authenticate subsequent API requests to protected resources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs