Perry Hoekstra
Perry Hoekstra

Reputation: 2763

Access AWS API Gateway from Axios

I am attempting to access AWS API Gateway-hosted services from Axios. Using AWS Amplify, I obtain a token using Auth.currentSession() which delivers a CognitoIdToken. Embedded within that object is a jwtToken. I have attempting to call my protected services (authorizer is set to AWS_IAM) using that jwtToken in the HTTP header, trying both the Authorization and x-api-key key, both with no joy. Given a CognitoIdToken/jwtToken, how do you call an AWS API Gateway service with an authorizer of AWS_IAM?

Upvotes: 2

Views: 4236

Answers (2)

Mahesh Mogal
Mahesh Mogal

Reputation: 658

I have been using API gateways along with Cognito for authorization for my Vuejs app. You can use following steps to get it configured easily.

  1. Select your API and go to Authorizers option on left panel. Click on Create New Authorizer. Then select cognito and add your Cognito user pool there. Name your Token Source as "Authorization". Keep token validation empty. Click on save.
  2. You can test your new authorizer using JWT token. You can print JWT token on console when you log in using AWS amplify and use that token for testing API authorizer. If you get user information from cognito pool, Your Authorizer is successfully configured.
  3. Next important step is to pass authorized user information from API to Lambda. You need to configure that in Integration request in your resource method. For this, select your method in API gateway and click on Integration Request, then click on Mapping Templates which is last option. Once you click that select 2nd radio button "When there are no templates defined (recommended)". After that in content type click on Add mapping template and give this template name as "application/json". Select this template and at bottom of screen you should see box. In that box you need to write template for getting cognito user details. You can refer following template.
#set($inputRoot = $input.path('$'))
{
    "cognitoUsername": "$context.authorizer.claims.email"
}

You can follow this link to get more details about template in AWS https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html

Hope this helps.

Upvotes: 0

Chris Pollard
Chris Pollard

Reputation: 1780

If you're using AWS_IAM authentication then you need to use AWS SigV4 with your access key, secret key, and session key that your cognito user gets as part of their authorization.

If you want to use the cognito JWT as your auth mechanism, you need to change your code to use cognito authentication at the API Gateway level.

Upvotes: 1

Related Questions