Securing API Gateway with API Keys
This tutorial references the code in the aws-connectedcar-dotnet-serverless repository. If you're new to this course, see the introduction for information about setting up your workstation and getting the sample code.
For the remaining tutorials in this section, we’re going to look at the three APIs in the sample code and see how each demonstrates a different way to secure API Gateway endpoints. We’ll start in this tutorial with the Admin API and its use of API keys to control access.
Defining a Usage Plan
Here’s the Auth element in the Admin API, as defined in the admin.yaml of the SAM deployment, which we’ve seen before:
The Auth element on lines 63-67 defines a new usage plan, which is an API Gateway resource that sets request quota and rate throttling properties for a set of client applications. API Gateway supports having multiple usage plans for third-party applications that can be regulated separately. In this case the SAM model supports the creation of one usage plan per API, with an associated API key for that plan. The "PER_API" property value can be changed to "SHARED" if the usage plan is to be shared across multiple APIs in the same template.
Getting the Generated API Key
Once deployed, the API key for the usage plan will be generated and can be viewed in the console, as shown below. Note that the value is not initially displayed on the page, so you have to click the “Show” link to see it:
As is sometimes the case for security-related resource properties, you can’t output the value of an API key in CloudFormation templates. However, you can write a script that combines a stack query with a call to the “get-api-keys” command to get the value, as shown below with the query-attributes.zsh script:
Applying API Keys in OpenAPI
With SAM templates, if you define a Usage Plan with API keys for the API resource, then the API keys are applied to all the endpoints in the API automatically. When using OpenAPI, however, there are two additions required. First, you need to add a “securitySchemes” element to the “components” section, as shown below. This example also specifies the location of the key in the request with the “in” property on line 473, and the name of the key on line 472. (These settings are unspecified defaults in the SAM deployment).
Then, for each endpoint, you need to add the “security” element, as shown below on lines 26-27:
Sending the API Key in Requests
With the settings shown above, client applications must include the API key in the HTTP headers of all requests, using the "x-api-key" header name. To illustrate, here’s the “Authorization” setup that uses these keys in the “Admin_API” Postman Collection. In this case, you set the “apiKey” value referenced below in the Postman global variables:
Note that this security mechanism can be used on its own, or in addition to, the other available security mechanisms that we will cover next.