Protect AWS API Gateway Endpoints using API Keys
AWS API Gateway offers various ways to protect API endpoints, most recently AWS announced Private Endpoints which are only accessible from VPC. In addition to that, you can protect APIs using the following methods
- Custom Authorizers
- API Keys
- Client Certificates
- Or a combination of these
In this post, we will cover the API keys method only. Using API keys you can also create Usage Plans which allows you to enable Throttling and Quota on the APIs.
In this example, we have an AWS lambda function which is exposed using the AWS API Gateway endpoint, we will protect the endpoint using API keys and test it using Postman tool. The API is called My API with a resource called hello and a GET method calling Lambda function hello-lambda as shown on the slide.
Before API key protection you can call the API using the browser or Postman
Create API Keys
The first step is to create API Keys, the steps are simple
- Log in to AWS Console and AWS API Gateway
- Click on API Keys then from the Actions drop-down list select Create API key
- Enter required API key name and description
Enable API Key on Method
Next is to enable your method to accept API Keys
Click on the API then Resources and click on the method you want to enable API keys, in our case it is hello/Get method
Click Method Request and select true from the API Key Required drop-down list
Create Usage Plan
Next step is to create a Usage Plan
Click on Usage Plan in AWS API Gateway Console then click Create
Enter Name of the plan, Throttling, and Quota info as per your requirement.
Practical Tip: You can create multiple usage plans and assign to different APIs, the plan will be enforced based on the API key, for example, you can have different membership levels such as Free, Basic and Pro plans and limit the quote and throttling accordingly.
Associate API stages to the plan, select API and the Stage as per your need, in our case it is my-api with test stage
Next is to associate API Keys to the plan, enter your API key name in the list, in our case it is my-api-key then click Done
Deploy the API
We need to deploy the API to take API keys in effect.
Click on the API then Resource, select Deploy API from the Actions drop-down, then select the stage you want to deploy
Testing the API
Now if you try to run the API in Postman or in the browser you will get the 403 Forbidden error message
We have to pass API Key in order this to work, copy the API key from API Keys in API Gateway Console
Pass the API key value in the Headers using x-api-key parameter