JAVASCRIPT
JavaScript: Implementing OAuth 2.0 Authorization Code Flow (Frontend)
Learn to initiate the OAuth 2.0 Authorization Code Flow in JavaScript, redirecting users for consent and handling the callback to exchange an authorization code for tokens.
function initiateOAuthFlow() {
const clientId = 'YOUR_CLIENT_ID';
const redirectUri = encodeURIComponent('http://localhost:3000/callback'); // Must match registered URI
const scope = encodeURIComponent('user:email repo'); // Scopes required by your application
const authUrl = 'https://github.com/login/oauth/authorize'; // Example: GitHub OAuth endpoint
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: redirectUri,
scope: scope,
response_type: 'code',
// Optional: state parameter for CSRF protection
state: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
});
// Store the state in sessionStorage or localStorage to verify on callback
sessionStorage.setItem('oauth_state', params.get('state'));
window.location.href = `${authUrl}?${params.toString()}`;
}
// Function to handle the callback after user authorization
async function handleOAuthCallback() {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
const storedState = sessionStorage.getItem('oauth_state');
if (!code) {
console.error('Authorization code not found in URL.');
return;
}
if (state !== storedState) {
console.error('State mismatch. Potential CSRF attack!');
return;
}
sessionStorage.removeItem('oauth_state'); // Clear state after verification
// Exchange authorization code for access token on your backend
// This step MUST happen on the backend to keep your client secret secure.
try {
const response = await fetch('/api/token', { // Your backend endpoint
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ code: code })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Access Token:', data.accessToken);
// Store access token (e.g., in localStorage, secure HTTP-only cookie)
// Redirect user to authenticated area
} catch (error) {
console.error('Error exchanging code for token:', error);
}
}
// Example usage:
// On button click: initiateOAuthFlow();
// On page load for the redirect URI: handleOAuthCallback();
How it works: This JavaScript snippet demonstrates the client-side steps of the OAuth 2.0 Authorization Code Flow. The `initiateOAuthFlow` function constructs an authorization URL with necessary parameters like `client_id`, `redirect_uri`, and `scope`, then redirects the user to the OAuth provider. A `state` parameter is included for CSRF protection and stored locally. The `handleOAuthCallback` function, meant for your `redirect_uri` page, extracts the `code` and `state` from the URL, verifies the state, and then sends the authorization `code` to your *backend* API to securely exchange it for an access token. The token exchange must happen on the backend to protect your `client_secret`.