简体   繁体   中英

When using Amazon API Gateway, how do I get the API key used in the request from a Django backend?

Pretty self explanatory title. I'm using API Gateway in AWS, requiring an API key to access a backend written in Django (not using lambda). I need to know how to access the API key used in the request to keep track of who did what at the app level.

You can use mapping templates and get the API Key from the $context variable, it's the apiKey property inside the identity object: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference

Create a mapping template for your requests and include the property in it. For example, if you wanted to include the entire request body + the API Key you would do this:

{
  "body": $input.json('$'),
  "apiKey": "$context.identity.apiKey"
} 

Depending on how your backend application is built, you could send the API key to your application in a HTTP parameter (path, query string, or header) or in the request body. Please have a read through the docs on how to move data between the two systems.

Thanks, Ryan

Here is how I finally made it work. At the top or bottom of the template, include this line.

#set($context.requestOverride.header.x-api-key = $context.identity.apiKey)

When your backend receives this request, the api key will be in the header x-api-key .

Here is a basic mapping template that just forwards the (json) body and the header.

$input.json("$")
#set($context.requestOverride.header.x-api-key = $context.identity.apiKey)

API Gateway uses the X-API-Key header, so I like for my backend to also use that. That way I can use the same testing commands with only the URL being different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM