JAVASCRIPT
OAuth 2.0 Client Credentials Flow for Server-to-Server Authentication
Securely obtain an access token using the OAuth 2.0 Client Credentials grant type in Node.js, ideal for server-to-server API integrations requiring programmatic access.
const axios = require('axios'); // or use node-fetch
async function getClientCredentialsToken(tokenUrl, clientId, clientSecret, scope = '') {
try {
const params = new URLSearchParams();
params.append('grant_type', 'client_credentials');
params.append('client_id', clientId);
params.append('client_secret', clientSecret);
if (scope) {
params.append('scope', scope);
}
const response = await axios.post(tokenUrl, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
// The response body usually contains:
// {
// "access_token": "...",
// "token_type": "Bearer",
// "expires_in": 3600,
// "scope": "..."
// }
return response.data.access_token;
} catch (error) {
console.error('Error obtaining client credentials token:', error.response ? error.response.data : error.message);
throw new Error('Failed to obtain access token.');
}
}
// Example Usage (replace with your actual values):
// const TOKEN_URL = 'https://your-oauth-provider.com/oauth/token';
// const CLIENT_ID = 'your_client_id';
// const CLIENT_SECRET = 'your_client_secret';
// const SCOPE = 'read:data write:data'; // Optional scope
// (async () => {
// try {
// const accessToken = await getClientCredentialsToken(TOKEN_URL, CLIENT_ID, CLIENT_SECRET, SCOPE);
// console.log('Access Token:', accessToken);
// // You can now use this token to make authenticated API requests
// // const apiResponse = await axios.get('https://api.example.com/resource', {
// // headers: { Authorization: `Bearer ${accessToken}` }
// // });
// // console.log('API Response:', apiResponse.data);
// } catch (error) {
// console.error(error.message);
// }
// })();
How it works: This Node.js snippet demonstrates how to implement the OAuth 2.0 Client Credentials Grant flow. This grant type is used for server-to-server communication where a confidential client (like a backend service) needs to access protected resources without user involvement. The function sends a POST request to the token endpoint with the `client_id`, `client_secret`, and `grant_type=client_credentials` parameters to obtain an access token, which can then be used in subsequent API requests.