JAVASCRIPT

Implementing OAuth 2.0 Client Credentials Flow (Node.js)

Securely obtain an access token for server-to-server API authentication using the OAuth 2.0 Client Credentials Grant Type in Node.js with `axios`.

const axios = require('axios');

async function getClientCredentialsToken(tokenUrl, clientId, clientSecret, scope = '') {
    try {
        const response = await axios.post(
            tokenUrl,
            new URLSearchParams({
                grant_type: 'client_credentials',
                client_id: clientId,
                client_secret: clientSecret,
                scope: scope
            }).toString(),
            {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json'
                }
            }
        );
        return response.data.access_token;
    } catch (error) {
        console.error('Error obtaining client credentials token:', error.response ? error.response.data : error.message);
        throw error;
    }
}

// Example Usage:
// const TOKEN_URL = 'https://example.com/oauth/token';
// const CLIENT_ID = process.env.OAUTH_CLIENT_ID;
// const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET;
// const SCOPE = 'api_read api_write'; // Optional

// (async () => {
//     try {
//         const token = await getClientCredentialsToken(TOKEN_URL, CLIENT_ID, CLIENT_SECRET, SCOPE);
//         console.log('Access Token:', token);
//         // Use the token to make API calls
//     } catch (err) {
//         console.error('Failed to get token:', err.message);
//     }
// })();
How it works: This Node.js snippet demonstrates the OAuth 2.0 Client Credentials flow, ideal for server-to-server communication where there's no user involved. It sends a `POST` request to the token endpoint with the `client_id` and `client_secret` to exchange them for an `access_token`. This token can then be used in subsequent API requests for authentication.

Need help integrating this into your project?

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

Hire DigitalCodeLabs