Making API calls with token

After sign-in and getting tokens, you can use these tokens to authorize access to protected APIs on API Gateway.

This exercise is based on the APIs that has been created in 2. Setup and Explore.

Important: Make sure that you have an API that uses Cognito authorizer for authorization using id_token. Remove Oauth Scopes from authorizer settings. Deploy to prod stage once done.

  1. Add the html layout for invoking APIs and rendering the results
<div id="callapis" class="w3-container w3-padding-large w3-grey tab" style="display:none">
    <button type="submit" class="w3-button w3-black w3-margin-bottom" onclick="callAPIGW()">Call APIGW</button>
    <div class="w3-section">
      <pre class="" id="apiresponse"></pre>
    </div>
</div>
  1. Add the function below to allow you to invoke APIs using the id-token of an authenticated user. Replace TYPE_YOUR_API_GATEWAY_ENDPOINT_URL with your API GW endpoint URL e.g. “https://[namerandom].execute-api.ap-southeast-2.amazonaws.com/prod/pets”
/**
 * Call protected APIGW endpoint
 *
 * Important:
 *   Make sure apigw cognito authorizer configuration is complete
 *   Make sure api accepts id-token (no oauth scope defined in authorization)
 *   You can only use id-token since custom scopes are not supported when sdk is used
 */
function callAPIGW(){

  apiGatewayUrl = "__TYPE_YOUR_API_GATEWAY_ENDPOINT_URL__";

  // set ID Token in "Authorization" header
  const headers = {
  	'Content-Type': 'application/json',
    'Authorization': cognitoUser.signInUserSession.idToken.jwtToken
  }

  axios.get(apiGatewayUrl, { headers: headers }).then((response) => {
    console.log(response.data);
    $("#apiresponse").html('<b>Response</b><br>'+JSON.stringify(response.data,null, 2));
  }).catch(function (error) {
    console.error(error);
  });
}

You can now test invoking the API, after you sign-in and get tokens from Cognito, navigate to “Call APIs” tab and click the Call APIGW button.

Notice the id-token is added to the authorization header and the endpoint responds with the expected results:

Note: If you received CORS error, make sure the APIs are configured to return “Access-Control-Allow-Origin” header for both 200 and 401 response codes (you will receive 401 if the token is invalid, expired or missing).