Hello,
I've run into an error trying to exchange the authorization code returned after a user is authenticated with AWS Cognito for an access token. The error logged on the console is "Error exchanging authorization code for tokens: Error: Token request failed with status 400". I've compared the syntax to the documentation here (https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html) and double-checked the other information, but I can't figure out where the issue is coming from. Why am I getting a bad request?
I've provided the code below. The exchangeCodeForTokens function contains the POST method that leads to the bad request error.
If someone could help me soon, I would greatly appreciate it!
Thanks,
Jared
function getAuthorizationCodeFromURL() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get("code");
}
async function exchangeCodeForTokens(authorizationCode){
const tokenEndpoint = "https://myDomain.auth.us-west-2.amazoncognito.com/oauth2/token";
const clientId = "myClientID";
const clientSecret = "myClientSecret";
const encodedAuthCode = btoa(clientId + ":" + clientSecret);
const authorizationString = "Basic " + encodedAuthCode;
console.log(authorizationString);
const redirectUri = "https://www.myDomain.com/menu.html"; //the configured redirect URI
try {
const response = await fetch(tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": authorizationString,
},
body: `grant_type=authorization_code&client_id=${clientId}&code=${authorizationCode}&redirect_uri=${redirectUri}`,
});
if (!response.ok) {
throw new Error(`Token request failed with status ${response.status}`);
}
const tokenData = await response.json();
return tokenData;
} catch (error) {
console.error("Error exchanging authorization code for tokens:", error);
throw error;
}
}
function parseUserIdFromToken(idToken){
// Decode the JWT part of the ID token using the atob function
const jwtPayload = JSON.parse(atob(idToken.split('.')[1]));
console.log(jwtPayLoad);
return jwtPayload.sub;
}
//usage:
const authorizationCode = getAuthorizationCodeFromURL();
console.log(authorizationCode);
exchangeCodeForTokens(authorizationCode)
.then((tokenData) => {
const accessToken = tokenData.access_token;
const idToken = tokenData.id_token;
// Parse user information from ID token
const userId = parseUserIdFromIdToken(idToken);
// Use the tokens and user information as needed
})
.catch((error) => {
console.log('error', error);
});