Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS-amplify Including the cognito Authorization header in the request

I have create an AWS mobile hub project including the Cognito and Cloud logic. In my API gateway, I set the Cognito user pool for the Authorizers. I use React native as my client side app. How can I add the Authorization header to my API request.

const request = {
  body: {
    attr: value
  }
};

API.post(apiName, path, request)
  .then(response => {
  // Add your code here
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
};
like image 738
Anson Cen Avatar asked Jun 01 '18 14:06

Anson Cen


1 Answers

By default, the API module of aws-amplify will attempt to sig4 sign requests. This is great if your Authorizer type is AWS_IAM.

This is obviously not what you want when using a Cognito User Pool Authorizer. In this case, you need to pass the id_token in the Authorization header, instead of a sig4 signature.

Today, you can indeed pass an Authorization header to amplify, and it will no longer overwrite it with the sig4 signature.


In your case, you just need to add the headers object to your request object. For example:

async function callApi() {

    // You may have saved off the JWT somewhere when the user logged in.
    // If not, get the token from aws-amplify:
    const user = await Auth.currentAuthenticatedUser();
    const token = user.signInUserSession.idToken.jwtToken;

    const request = {
        body: {
            attr: "value"
        },
        headers: {
            Authorization: token
        }
    };

    var response = await API.post(apiName, path, request)
        .catch(error => {
            console.log(error);
        });

    document.getElementById('output-container').innerHTML = JSON.stringify(response);
}

Tested using aws-amplify 0.4.1.

like image 145
Mike Patrick Avatar answered Sep 22 '22 18:09

Mike Patrick