oauth2 token endpoint invalid_request error.

0

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.

   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`; 

with axios

    axios
      .post(
        `${AUTH_DOMAIN}/oauth2/token`,

        new URLSearchParams({
          grant_type: grantType,
          code: code,
          state: state,
          client_id: clientId,
          redirect_uri: redirectUri
        }),
        {
          headers: {
            Authorization: getBase64EncodedCredential(clientId, clientSecret)
          }
        }
      )
      .then((response) => {
        // handle success
        console.log(response.data);
      })
      .catch((error) => {
        // handle error
        console.error(error);
      });

with fetch:

    const getToken = async (code) => {
      const url = `https://diplomade.auth.us-east-1.amazoncognito.com/oauth2/token`;

      const options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: getBase64EncodedCredential(clientId, clientSecret)
        },
        body: `grant_type=authorization_code&client_id=${clientId}&redirect_uri=${redirectUri}&code=${code}`
      };

      const response = await fetch(url, options);
      const data = await response.json();

      return data.access_token;
    };
  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 am getting error: "invalid_grant" for the same code. I do not understand where i am doing wrong.

I have also applied this answer but still getting the same error.

  • please help!

No Answers

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions