JAVASCRIPT
Authenticating API Requests with Bearer Tokens in JavaScript
Securely make authenticated API requests by including a Bearer token in the Authorization header of your JavaScript Fetch API calls, ensuring access to protected endpoints.
async function callAuthenticatedApi(url, token, method = 'GET', data = null) {
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}` // Include the Bearer token
};
const options = {
method: method,
headers: headers,
};
if (data && (method === 'POST' || method === 'PUT')) {
options.body = JSON.stringify(data);
}
try {
const response = await fetch(url, options);
if (!response.ok) {
// Handle specific authentication errors (e.g., 401 Unauthorized, 403 Forbidden)
if (response.status === 401) {
console.error("Authentication failed: Invalid or expired token.");
// Optionally, redirect to login page or refresh token
} else if (response.status === 403) {
console.error("Authorization failed: Not permitted to access this resource.");
}
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
return result;
} catch (error)
{
console.error("Failed to call authenticated API:", error);
throw error;
}
}
// Example Usage:
// const MY_AUTH_TOKEN = 'your_actual_bearer_token_here'; // Get this from localStorage, sessionStorage, or state
// const PROTECTED_API_URL = 'https://api.example.com/protected-data';
// async function getProtectedData() {
// if (!MY_AUTH_TOKEN) {
// console.error("Auth token is missing. Please log in.");
// return;
// }
// try {
// const data = await callAuthenticatedApi(PROTECTED_API_URL, MY_AUTH_TOKEN);
// console.log('Protected data:', data);
// } catch (error) {
// console.error('Failed to get protected data:', error);
// }
// }
// getProtectedData();
// Example for POST with token:
// async function postProtectedData() {
// if (!MY_AUTH_TOKEN) {
// console.error("Auth token is missing. Please log in.");
// return;
// }
// const postData = {
// name: 'New Item',
// value: 123
// };
// try {
// const result = await callAuthenticatedApi(PROTECTED_API_URL, MY_AUTH_TOKEN, 'POST', postData);
// console.log('Protected POST result:', result);
// } catch (error) {
// console.error('Failed to post protected data:', error);
// }
// }
// postProtectedData();
How it works: This JavaScript snippet illustrates how to make authenticated requests to an API using a Bearer token. The token, typically obtained after a user logs in, is securely included in the `Authorization` header of the HTTP request. The `fetch` API is used to perform the request, and the snippet also incorporates error handling, specifically addressing common authentication-related HTTP status codes like 401 (Unauthorized) and 403 (Forbidden), which is crucial for interacting with protected API endpoints.