JAVASCRIPT
Implementing OAuth 2.0 Client Credentials Grant for Server-to-Server API Calls
Shows how to securely obtain an access token using OAuth 2.0 Client Credentials flow for server-to-server communication with external APIs.
const axios = require('axios'); // or use native fetch
const OAUTH_CONFIG = {
TOKEN_URL: 'https://api.example.com/oauth/token',
CLIENT_ID: process.env.OAUTH_CLIENT_ID,
CLIENT_SECRET: process.env.OAUTH_CLIENT_SECRET,
SCOPE: 'read write', // Optional: define required scopes
};
let accessToken = null;
let tokenExpiry = 0; // Timestamp in milliseconds
async function getAccessToken() {
if (accessToken && Date.now() < tokenExpiry - 5000) { // Refresh 5 seconds before actual expiry
console.log('Using cached access token.');
return accessToken;
}
console.log('Fetching new access token...');
try {
const authHeader = Buffer.from(`${OAUTH_CONFIG.CLIENT_ID}:${OAUTH_CONFIG.CLIENT_SECRET}`).toString('base64');
const response = await axios.post(
OAUTH_CONFIG.TOKEN_URL,
new URLSearchParams({
grant_type: 'client_credentials',
scope: OAUTH_CONFIG.SCOPE,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${authHeader}`,
},
}
);
accessToken = response.data.access_token;
tokenExpiry = Date.now() + (response.data.expires_in * 1000); // expires_in is usually in seconds
console.log('New access token obtained.');
return accessToken;
} catch (error) {
console.error('Error fetching OAuth token:', error.response ? error.response.data : error.message);
throw new Error('Failed to obtain OAuth access token.');
}
}
// Example usage:
async function callProtectedApi() {
try {
const token = await getAccessToken();
const apiResponse = await axios.get('https://api.example.com/protected-resource', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
console.log('Protected API response:', apiResponse.data);
} catch (error) {
console.error('Error calling protected API:', error.message);
}
}
// Call the example function
// callProtectedApi();
How it works: This Node.js snippet demonstrates how to implement the OAuth 2.0 Client Credentials grant flow. This flow is used for server-to-server communication where a specific user's context is not required. The code obtains an access token by sending the client ID and secret to the authorization server. It includes basic token caching and refreshing logic to avoid unnecessary token requests and ensures tokens are used before expiration, enhancing efficiency and security for API integrations.