JAVASCRIPT

Implementing OAuth 2.0 Client Credentials Flow for API Access

Securely access APIs from your server using the OAuth 2.0 Client Credentials Grant, ideal for server-to-server communication without user interaction.

// Example using Node.js with 'node-fetch'
const fetch = require('node-fetch'); // or use native fetch in newer Node.js

const TOKEN_URL = 'https://your-auth-server.com/oauth/token';
const CLIENT_ID = 'your_client_id';
const CLIENT_SECRET = 'your_client_secret';
const SCOPE = 'read write'; // Optional, depending on API

async function getAccessToken() {
    try {
        const authHeader = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');
        const response = await fetch(TOKEN_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${authHeader}`
            },
            body: new URLSearchParams({
                grant_type: 'client_credentials',
                scope: SCOPE
            }).toString()
        });

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

        const data = await response.json();
        return data.access_token;

    } catch (error) {
        console.error('Error fetching OAuth token:', error.message);
        throw error;
    }
}

// Example usage:
// (async () => {
//     try {
//         const token = await getAccessToken();
//         console.log('Access Token:', token);
//         // Use the token to make API calls
//         // const apiResponse = await fetch('https://your-api.com/data', {
//         //     headers: {
//         //         'Authorization': `Bearer ${token}`
//         //     }
//         // });
//         // const apiData = await apiResponse.json();
//         // console.log('API Data:', apiData);
//     } catch (e) {
//         console.error('Application failed:', e);
//     }
// })();
How it works: This snippet demonstrates the OAuth 2.0 Client Credentials grant flow. It's used for server-to-server communication where a web application needs to access an API on its own behalf, not on behalf of an end-user. The client sends its ID and secret to the authorization server to obtain an access token, which is then used to authorize subsequent API requests. This method is highly secure for machine-to-machine interactions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs