🔐 API Authentication = Secure Access
APIs need security. JWT, OAuth, API Keys — choose the right authentication. Protect your API, secure data.
📝 JWT Authentication
// Login - Get JWT token
async function login(email, password) {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const data = await response.json();
if (data.token) {
localStorage.setItem('token', data.token);
return data;
}
throw new Error('Login failed');
}
// Attach token to requests
async function fetchWithAuth(url, options = {}) {
const token = localStorage.getItem('token');
const headers = {
...options.headers,
'Authorization': `Bearer ${token}`
};
const response = await fetch(url, {
...options,
headers
});
if (response.status === 401) {
// Token expired - refresh or redirect to login
localStorage.removeItem('token');
window.location.href = '/login';
}
return response;
}
🎯 Authentication Methods
# API Key (Simple)
fetch('https://api.example.com/data', {
headers: {
'X-API-Key': 'your-api-key-here'
}
});
# OAuth2 (External providers)
// 1. Redirect to provider
window.location.href = 'https://auth.example.com/authorize?client_id=CLIENT_ID&redirect_uri=CALLBACK_URL';
// 2. Handle callback
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
// 3. Exchange code for token
async function exchangeCode(code) {
const response = await fetch('/api/auth/exchange', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code })
});
const data = await response.json();
localStorage.setItem('token', data.token);
}
# Basic Auth
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Basic ' + btoa('username:password')
}
});
💡 Authentication Best Practices
- Use HTTPS for all requests
- Store tokens securely (HTTP-only cookies)
- Implement token refresh
- Use short-lived access tokens
- Validate tokens server-side
“API authentication is security. JWT, OAuth, API Keys. Essential for API development.”
