To initiate the authorization flow, redirect the user to the authorization endpoint with these required parameters:
// Request User Authorization
const authorizationUrl = new URL(`${authServerUrl}/protocol/openid-connect/auth`);
authorizationUrl.searchParams.append('response_type', 'code');
authorizationUrl.searchParams.append('client_id', clientId);
authorizationUrl.searchParams.append('redirect_uri', redirectUri);
authorizationUrl.searchParams.append('scope', 'openid profile email');
authorizationUrl.searchParams.append('state', generateRandomState());
// Redirect user to authorization URL
window.location.href = authorizationUrl.toString();Required Parameters:
response_type: Set to "code"client_id: Your application's client IDredirect_uri: URL to return to after authenticationscope: Requested permissions (e.g., "openid profile email")state: Random string to prevent CSRF attacksAfter receiving the authorization code, exchange it for an access token:
// Exchange authorization code for tokens
async function exchangeCodeForToken(code) {
const response = await fetch(`${authServerUrl}/protocol/openid-connect/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: clientId,
client_secret: clientSecret,
code: code,
redirect_uri: redirectUri
})
});
const tokens = await response.json();
return tokens;
// Returns: { access_token, refresh_token, id_token }
}Required Parameters:
grant_type: Set to "authorization_code"client_id: Your application's client IDclient_secret: Your application's client secretcode: The authorization code receivedredirect_uri: Same URL used in authorization requestThe response will include:
access_token: Use this to access protected resourcesrefresh_token: Use this to get new access tokensid_token: Contains user information (if requested)token_type: Usually "Bearer"expires_in: Token lifetime in seconds