JAVASCRIPT
Implement OAuth 2.0 Client Credentials Flow for Server-to-Server API Access
Learn to securely authenticate server-to-server API calls using the OAuth 2.0 Client Credentials grant type in Node.js, ideal for service integrations.
const axios = require('axios');
const TOKEN_URL = 'YOUR_OAUTH_TOKEN_ENDPOINT';
const CLIENT_ID = process.env.OAUTH_CLIENT_ID; // Stored securely
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET; // Stored securely
const API_URL = 'YOUR_PROTECTED_API_ENDPOINT';
async function getAccessToken() {
try {
const response = await axios.post(
TOKEN_URL,
'grant_type=client_credentials', // Required grant type
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`,
},
}
);
return response.data.access_token;
} catch (error) {
console.error('Error getting access token:', error.response ? error.response.data : error.message);
throw new Error('Failed to retrieve access token.');
}
}
async function callProtectedApi() {
try {
const accessToken = await getAccessToken();
console.log('Access Token acquired:', accessToken.substring(0, 10) + '...'); // Log a partial token for security
const response = await axios.get(API_URL, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
console.log('API Response Data:', response.data);
return response.data;
} catch (error) {
console.error('Error calling protected API:', error.response ? error.response.data : error.message);
throw new Error('Failed to call protected API.');
}
}
// Example usage
// callProtectedApi().then(() => console.log('API call complete.'));
How it works: The OAuth 2.0 Client Credentials flow is designed for server-to-server communication where a service needs to access protected resources without a user's direct involvement. This snippet demonstrates how to first obtain an `access_token` from an OAuth provider using a `CLIENT_ID` and `CLIENT_SECRET`. This token is then included as a `Bearer` token in the `Authorization` header for subsequent requests to the protected API, ensuring secure and authorized access.