AWS-amplify Including the cognito Authorization header in the request
Asked Answered
S

2

13

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);
  });
};
Susansusana answered 1/6, 2018 at 14:1 Comment(0)
D
30

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.

Deccan answered 2/6, 2018 at 17:43 Comment(1)
I'm getting error 304 IncompleteSignatureExceptionSkeen
S
1

The accepted answer only works if your endpoint doesn't have aws_iam authorization, otherwise you'll hit IncompleteSignatureException. The solution is attach the id_token to a custom header (eg: jwt-token) and remember to whitelist that custom header in your apigateway.

Strophanthin answered 28/6, 2023 at 23:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.