JAVASCRIPT
Obtaining OAuth 2.0 Access Token with Client Credentials Grant
Learn how to securely obtain an OAuth 2.0 access token using the client credentials grant flow for server-to-server API integrations with Node.js.
const fetch = require('node-fetch');
const clientId = process.env.OAUTH_CLIENT_ID;
const clientSecret = process.env.OAUTH_CLIENT_SECRET;
const tokenUrl = 'https://api.example.com/oauth/token'; // Your OAuth provider's token endpoint
async function getAccessToken() {
try {
const response = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + Buffer.from(`${clientId}:${clientSecret}`).toString('base64'),
},
body: 'grant_type=client_credentials',
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Failed to get access token: ${response.status} ${response.statusText} - ${errorBody}`);
}
const data = await response.json();
console.log('Access Token:', data.access_token);
console.log('Expires In:', data.expires_in);
return data.access_token;
} catch (error) {
console.error('Error during token retrieval:', error.message);
throw error;
}
}
// Example usage:
// getAccessToken().then(token => {
// // Use the token for subsequent API calls
// }).catch(err => {
// console.error('Application failed to start due to OAuth error.');
// });
How it works: This snippet demonstrates the OAuth 2.0 Client Credentials Grant flow, which is ideal for server-to-server communication where there's no end-user involvement. It sends a POST request to the OAuth provider's token endpoint, including the client ID and secret encoded in the Authorization header. The `grant_type=client_credentials` in the request body specifies the grant type. Upon success, the API returns an access token, which can then be used to authenticate subsequent requests to protected API resources.