- Hands-On Serverless Applications with Kotlin
- Hardik Trivedi Ameya Kulkarni
- 425字
- 2025-02-26 15:24:31
API keys and usage plans
API keys are a well-known concept. They are like gate passes for accessing a particular realm. They comprise the first level of access control that APIs impose.
Let's look at a real-world example. Suppose that Harry is a traveler that wants to travel to a particular location by plane. Harry needs to catch a flight from an airport.
For security reasons, the airport is a strictly access-controlled location. Only folks that have a valid ID card or passport and a plane ticket for that day are allowed to enter. There are further authentications and authorizations that the passenger has to undergo before boarding the flight, but none of them will occur if the passenger is not let on due to invalidity of his/her ID card or ticket.
One can think of the ID card and the ticket as the API keys. They are necessary for the passenger (a client) to access the airport (the resources/locations), but are not sufficient to fully use the service.
The Amazon API Gateway uses the concept of API keys. One can choose to have an API key associated with a resource method by following these steps:
- Issue an API key
- Create a usage plan
- Associate the key with the usage plan
- Associate the usage plan with an API stage
The following screenshots illustrate the process of configuring the API key for the Greeter API:
- In the details for a method, specify that an API key is required, as follows:
- The API key details should be as follows:
Note the API key value, 1fmETyfh8x7OazCD4nPvd9WkUPM0An953mkmpmoN. This is the value that the client will have to pass.
- Create a Usage Plan, as follows:
- Associate the greeter-api-key with the usage plan that was just created, as follows:
- Associate the usage plan with the test stage of the Greeter API, as follows:
Now that we have created an API key and a usage plan and have associated them, it's time to test the setup.
Let's invoke the Greeter API on test, without passing in the auth key. As the output shows, the client can't access the API, and gets a 403 error code:
Ameyas-MacBook-Pro:~ Webonise$ curl -X POST https://8uf5e3eccd.execute-api.us-west-1.amazonaws.com/test/greeter -d '"ameya"'
{"message":"Forbidden"}
Let's invoke the Greeter API on the test stage by passing in the API key as a header (x-api-key):
Ameyas-MacBook-Pro:~ Webonise$ curl -X POST -H 'x-api-key:1fmETyfh8x7OazCD4nPvd9WkUPM0An953mkmpmoN' https://8uf5e3eccd.execute-api.us-west-1.amazonaws.com/test/greeter -d '"ameya"'
"Hello, ameya on Fri Jul 20 14:55:07 UTC 2018"