DEV Community

Joshua Kahn
Joshua Kahn

Posted on • Originally published at blog.iamjkahn.com on

Calling Amazon API Gateway Authenticated Methods with axios and aws4

Amazon API Gateway provides a convenient, easy-to-use service that allows developers to publish, monitor, and maintain APIs. It also provides a separation of concerns between your custom business logic and common needs such as caching, throttling, and authorization.

For a recent project, I needed to secure my APIs such that only authorized users could call them (e.g. administrator endpoints). API Gateway supports a number of approaches to controlling access to your services. I also needed to provide authentication for a pool of users and opted to leverage AWS’s powerful IAM capability to control access via Amazon Cognito. Cognito provides both user management as well as federated identity to provide secure access to AWS resources, including calling an API Gateway method.

Enough background, on to the code…

On the frontend, I used the popular axios HTTP library in addition to aws4, a library to sign requests using AWS Signature v4. While the configuration of API Gateway is beyond the scope of this post, know that we need to sign and provide an Authentication header in order for the call to be allowed by secured APIs. This is what aws4 helps to enable. Signing the requests allows the frontend to assume an AWS Role authorized to call the API.

Note: the following code snippets assume the user has already authenticated via Cognito and retrieved temporary credentials (including an access key, secret key, and session token).

First, the following code demonstrates a GET to an API secured with AWS_IAM authorization:

400: Invalid request

Next, let’s consider how the above changes for a PUT request. Note the addition to the request body as well as a content-type header.

400: Invalid request

I hope you found the above useful as you work with these great frontend packages and Amazon API Gateway.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay