[英]How to access HTTP headers for request to AWS API Gateway using Lambda?
I see in the API Gateway FAQ that it is possible to access the request headers sent to the API Gateway...我在API 网关常见问题解答中看到可以访问发送到 API 网关的请求标头...
If you already utilize OAuth tokens or any other authorization mechanism, you can easily setup API Gateway not to require signed API calls and simply forward the token headers to your backend for verification.
如果您已经使用 OAuth 令牌或任何其他授权机制,您可以轻松设置 API 网关不需要签名的 API 调用,只需将令牌标头转发到您的后端进行验证。
However, I can find no example of how to do so in the documentation and it is unclear how to access this data using Lambda.但是,我在文档中找不到如何执行此操作的示例,也不清楚如何使用 Lambda 访问此数据。
I am able to set up an open API and gain access to the JSON object that is part of a POST ( Walkthrough: API Gateway and Lambda Functions ), but in order to implement a OAuth 2.0 style API with my own provider I need access to the "Authorization" header.我能够设置一个开放的 API 并获得对作为 POST 一部分的 JSON 对象的访问权限( 演练:API 网关和 Lambda 函数),但是为了使用我自己的提供程序实现 OAuth 2.0 样式的 API,我需要访问“授权”标头。
My preference is to set this up using Lambda and Java 8, but an example using node.js would also be helpful in understanding how to accomplish this.我的偏好是使用 Lambda 和 Java 8 进行设置,但使用 node.js 的示例也有助于理解如何完成此操作。
First, you need to trap the Authorization
header from the HTTP GET request. 首先,您需要从HTTP GET请求中捕获
Authorization
标头。 Then you need to map that value to the Lambda event object. 然后,您需要将该值映射到Lambda事件对象。
Go to the API method dashboard and click on Method Request. 转到API方法仪表板,然后单击“方法请求”。 In there you can add an
HTTP Request Header
called Authorization
as shown below. 您可以在其中添加一个称为
Authorization
的HTTP Request Header
,如下所示。
This will trap the Authorization
header so you can use it later. 这将捕获
Authorization
标头,以便您以后使用。
Now go back to the method dashboard and click on Integration Request
. 现在返回方法仪表板,然后单击
Integration Request
。 From here you can pass the value of the header into the Lambda function by using a mapping like this. 在这里,您可以通过使用这样的映射将标头的值传递给Lambda函数。
{
"Authorization": "$input.params('Authorization')"
}
Now in your Lambda function you can get the value like this. 现在,在Lambda函数中,您可以像这样获得值。
event.Authorization
You can use the following Mapping Template in the Integration Request to generically map all path, query, and header parameters into the Lambda event. 您可以在集成请求中使用以下映射模板将所有路径,查询和标头参数一般映射到Lambda事件中。 You will still need to register them in the Method Request section of the API Gateway but you can at least decouple the Mapping Template from the specific parameters you want to use.
您仍然需要在API网关的“方法请求”部分中注册它们,但是至少可以将映射模板与要使用的特定参数分离。 This way you don't have to change the Mapping Template code each time you change headers, query, or path parameters.
这样,您不必在每次更改标题,查询或路径参数时都更改映射模板代码。
I wrote a blog post that gives more detail and some explanation of the Mapping Template: http://kennbrodhagen.net/2015/12/06/how-to-create-a-request-object-for-your-lambda-event-from-api-gateway/ 我写了一篇博客文章,其中提供了有关映射模板的更多详细信息和一些解释: http : //kennbrodhagen.net/2015/12/06/how-to-create-a-request-object-for-your-lambda-event -从API网关/
Here is the Mapping Template you can use: 这是您可以使用的映射模板:
{
"method": "$context.httpMethod",
"body" : $input.json('$'),
"headers": {
#foreach($param in $input.params().header.keySet())
"$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end
#end
},
"queryParams": {
#foreach($param in $input.params().querystring.keySet())
"$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end
#end
},
"pathParams": {
#foreach($param in $input.params().path.keySet())
"$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end
#end
}
}
You need to create input mapping inside Integration Request
panel on the dashboard screen describing your API method. 您需要在仪表板屏幕上的“
Integration Request
面板中创建描述您的API方法的输入映射。
Following code translates name
query input parameter into Lambda Event input object
: 以下代码将
name
查询输入参数转换为Lambda Event input object
:
{
"name": "$input.params('name')"
}
Screenshot: 屏幕截图:
You can find more info about this in the original API Gateway to Lambda input thread on AWS Forums . 您可以在AWS Forums上的原始API Gateway to Lambda输入线程中找到有关此的更多信息。
while this is an old thread, I have found it best to use lambda proxy integration for the purpose. 虽然这是一个旧线程,但我发现最好是为此目的使用lambda代理集成。 With this you do not have to configure anything in the API gateway and you get all the headers in your lambda function...
有了这个,您不必在API网关中进行任何配置,您就可以在lambda函数中获得所有标头...
As per Prabhat's answer setting up with the lambda proxy integration request is the simplest way to do this, after which you can access the request headers, path parameters and query parameters via 根据Prabhat的回答,使用lambda代理集成请求进行设置是执行此操作的最简单方法,之后您可以通过以下方式访问请求标头,路径参数和查询参数
event['pathParameters']['param1']
event["queryStringParameters"]['queryparam1']
event['requestContext']['identity']['userAgent']
event['requestContext']['identity']['sourceIP']
The solution by kennbrodhagen worked great for me, see his answer and blog for the details. kennbrodhagen的解决方案对我来说非常有效,请参阅他的答案和博客以获取详细信息。 Since the poster expressed a preference for Java implementation, and it took me a while to figure out how to implement Kenn's handler in java, I'm just sharing the Java code that corresponds:
由于发帖人表达了对Java实现的偏爱,并且花了我一段时间才弄清楚如何在Java中实现Kenn的处理程序,所以我只是共享对应的Java代码:
public class MyHandler implements RequestHandler<Map<String,Object>,String> {
@Override
public String handleRequest(Map<String,Object> eventMap, Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Body:" + eventMap.get("body"));
logger.log("Headers:" + eventMap.get("headers"));
logger.log("Method:" + eventMap.get("method"));
logger.log("Params:" + eventMap.get("params"));
logger.log("Query:" + eventMap.get("query"));
return("{}");
}
}
This is an example event object: 这是一个示例事件对象:
{
"requestContext": {
"elb": {
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a"
}
},
"httpMethod": "GET",
"path": "/lambda",
"queryStringParameters": {
"query": "1234ABCD"
},
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"accept-encoding": "gzip",
"accept-language": "en-US,en;q=0.9",
"connection": "keep-alive",
"host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476",
"x-forwarded-for": "72.12.164.125",
"x-forwarded-port": "80",
"x-forwarded-proto": "http",
"x-imforwards": "20"
},
"body": "",
"isBase64Encoded": false
} }
The event object contains "headers"
in it, you can access request headers sent to API gateway by using: event.headers.<header key>
事件对象中包含
"headers"
,您可以使用以下方法访问发送到API网关的请求标头: event.headers.<header key>
If you have enabled Lambda Proxy integration you just have to check the Headers
collection in your Lambda handler:如果您启用了Lambda 代理集成,您只需检查 Lambda 处理程序中的
Headers
集合:
public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest data, ILambdaContext context)
{
if (data.Headers.ContainsKey("x-api-key"))
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.