aws cognito oauth2 token endpoint returns invalid_request error

1.1k Views Asked by At

I am using Authorization code grant to create a new cognito user object, but got invalid_request as response. I have got code and state from redirected url but cannot get id,access and refresh tokens to create a cognito user.

I am getting code from cognito successfully in url like so:

http://localhost:3000/login-google?code=xxx-xxx-xxx-xxx-xxxxx&state=xxxxxxx

const AUTH_DOMAIN = 'https://xxx.auth.us-east-1.amazoncognito.com';
const grantType = 'authorization_code';
const clientId = 'xxx'; 
const clientSecret = 'xxxx',
const redirectUri = `${window.location.origin}/login-google`; 
    axios
  .post(
    `${AUTH_DOMAIN}/oauth2/token`,

    new URLSearchParams({
      grant_type: grantType,
      code: code,
      state: state,
      client_id: clientId,
      redirect_uri: redirectUri
    }),
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: getBase64EncodedCredential(clientId, clientSecret)
      }
    }
  )
  .then((response) => {
    // handle success
    console.log(response.data);
  })
  .catch((error) => {
    // handle error
    console.error(error);
  });
  function getBase64EncodedCredential(cognitoAppId, cognitoAppSecret) {
return 'Basic ' + btoaImplementation(cognitoAppId + ':' + cognitoAppSecret);
}
 function btoaImplementation(str) {
  try {
  return btoa(str);
  } catch (err) {
  return Buffer.from(str).toString('base64'); //btoa is not implemented in node.js.
 }
}

I have pre-toke lambda function but i think it does not affect it, since i got same error when i remove it.

I have look through this post and this post but could not able to find a solution.

"aws-amplify": "^5.0.17",
"amazon-cognito-identity-js": "^6.1.2",
"react": "^18.2.0",
1

There are 1 best solutions below

3
Gary Archer On

You should add the authorization request you are sending to the question, and also the error response. In axios, also send this header, and avoid sending the client_id in the POST body:

'content-type': 'application/x-www-form-urlencoded',

If you sent a code_challenge on the authorization request you need to send a code_verifier in the POST request.

Out of interest, this code of mine has some working axios / cognito requests. You should be able to get it working based on that.