简体   繁体   English

如何配置serverless.yml或AWS API网关或AWS Lambda处理程序以从POST请求读取request.header

[英]How to configure serverless.yml or AWS API gateway or AWS lambda handler to read request.headers from POST request

I was trying to deploy a API created with flask and serverless framework to AWS lambda and API gateway, however I was not able to read the proper header. 我试图将使用flaskserverless framework创建的API部署到AWS Lambda和API网关,但是我无法读取正确的标头。

I did read some post from https://stackoverflow.com/a/43830950/2806237 , which indicates that request details will be available in event of the handler function. 我确实从https://stackoverflow.com/a/43830950/2806237阅读了一些文章,该文章指示在处理程序功能event时,请求详细信息将可用。

However, I am use wsgi.handler as my handler, so how am I supposed to read event variable which exists in wsgi.hander ? 但是,我将wsgi.handler用作处理程序,所以我应该如何读取wsgi.hander中存在的event变量? Should I create my own handler or I can get the request details of event from somewhere? 我应该创建自己的处理程序,还是可以从某处获取event的请求详细信息?

FYI, I am using AWS V4 signature to sign each request from both client side and server side, then compare each signature to ensure the request is secured. 仅供参考,我正在使用AWS V4签名对客户端和服务器端的每个请求进行签名,然后比较每个签名以确保请求得到保护。 This will generate a header like below: 这将生成如下所示的标头:

Host: 10.0.0.48:9998
Connection: keep-alive
Content-Length: 37
Origin: xxxxxxxxxxxxxxxxxxxx
Authorization: AWS4-HMAC-SHA256 Credential=usernameHere/20181220///aws4_request, SignedHeaders=content-length;content-type;host;x-amz-content-sha256;x-amz-date;x-amz-target, Signature=c57780866a6380b92678e8a9d52d8220d3ecc836f4475b8334c553cf4dbb9ad4
Content-Type: application/json;charset=UTF-8
X-Amz-Content-Sha256: 615d42718684ea2b59442a6ce3dc6302404839b0875bca365a6e07e0d65f577c
Accept: application/json, text/javascript, */*; q=0.01
X-Amz-Target: SchoolLearnMeter_1980121.GetPassword
X-Amz-Date: 20181220T021132Z
User-Agent: Mozilla/5.0 (X11; CrOS x86_64 11210.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3593.0 Safari/537.36
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9.

However,the header I am getting like this: 但是,我得到的标题是这样的:

Content-Length: 36
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip, deflate
Cache-Control: no-cache
Cloudfront-Forwarded-Proto: https
Cloudfront-Is-Desktop-Viewer: true
Cloudfront-Is-Mobile-Viewer: false
Cloudfront-Is-Smarttv-Viewer: false
Cloudfront-Is-Tablet-Viewer: false
Cloudfront-Viewer-Country: AU
Host: XXXXX.execute-api.ap-southeast-2.amazonaws.com
Postman-Token: 8742a77d-4e1a-4d0c-ba6a-6df15795e7c8
User-Agent: PostmanRuntime/7.4.0
Via: 1.1 098fddbcdf00e65b8479d1d17b41d28a.cloudfront.net (CloudFront)
X-Amz-Cf-Id: HafOPHJfXOungGylHkX4Y3klvdBR-kzoC-xz1aqNXo-4K2KbbsD_lg==
X-Amz-Date: 20181220T034409Z
X-Amzn-Trace-Id: Root=1-5c1b100a-7a69d8e08c9ee3e0e6b799e0
X-Forwarded-For: 115.187.209.206, 70.132.29.75
X-Forwarded-Port: 443
X-Forwarded-Proto: https 

This is the application.py code 这是application.py代码

from flask import Flask, request, jsonify
import os, sys
import hashlib
import json
from dbConnection import DBConncetion
from awssigner import AWSSigner

application = Flask(__name__)
db_conn_str = os.environ["Chrome_DB"]
responseMessage = {"ResponseMessage":""}

@application.route("/u", methods=["POST"])
def getUserPasswordByUsername():
    try:
        serverSignature = AWSSigner(request).getSignature(json.dumps(request.get_json(Force=true)).replace(": ",":"))
        agentSignature = request.headers.get("Authorization").split("Signature=",1)[1]
        if(serverSignature == agentSignature):
            #Do something here
        else:
            raise Exception
    except:
        responseMessage["ResponseMessage"] = "There are some errors occured, please try again later"
        response = application.response_class(
            response= json.dumps(responseMessage),
            status=500,
            mimetype = "application/json"
        )
        return response

if __name__ == "__main__":
    application.run()
    #application.run("0.0.0.0", 9998, debug = True)

This is the serverless.yml file 这是serverless.yml文件

service: testapiservices

plugins:
 - serverless-python-requirements
 - serverless-wsgi

custom:
 wsgi:
   app: application.application
   packRequirements: false
 pythonRequirements:
   dockerizePip: non-linux

provider:
 name: aws
 runtime: python3.7
 stage: dev
 region: ap-southeast-2

functions:
 app:
   handler: wsgi.handler
   environment:
     AppId: XXX
     Chrome_DB: XXX
   events:
     - http:
         cors: true
         method: post
         path: /
     - https: 'ANY{proxy+}'
   vpc:
     securityGroupIds:
       - XXX
     subnetIds:
       - XXX
       - XXX

serverless-wsgi provides a flask wrapper for you to use, so it actually handles the event variable in the background and maps it to a Flask request . serverless-wsgi提供了一个Flask包装器供您使用,因此它实际上在后台处理event变量并将其映射到Flask request

Import the flask request object, and use that in your code instead: 导入flask请求对象,并在代码中使用它:

from flask import Flask, request

Read the Flask docs around the request but it will have all the headers etc you would expect in the lambda event 阅读有关request的Flask文档,但它将包含您在lambda event期望的所有标头等

Also you are using agent User-Agent: PostmanRuntime/7.4.0 to send the request that gives the second set of headers. 另外,您还使用代理User-Agent: PostmanRuntime/7.4.0发送具有第二组标头的请求。 You literally as a developer set those headers, so I'm confused why you would expect them to match unless you set them to match. 您实际上是作为开发人员设置这些标头的,所以我很困惑为什么您希望它们匹配,除非您将它们设置为匹配。

What header are you specifically looking to check? 您要具体检查哪个标头?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用AWS Web API和Lambda验证无服务器Web请求? - How to authenticate serverless web request using AWS Web API and Lambda? 如何在 serverless.yml 中为 AWS SQS 设置 maximumBatchingWindowInSeconds? - How to set maximumBatchingWindowInSeconds for AWS SQS in serverless.yml? 如何使用 Ansible 将 AWS API 网关集成请求正确设置为 lambda 函数? - How to set AWS API gateway integration request to lambda function correctly using Ansible? 在 python 中使用 AWS Lambda 向外部 API 发送 Post 请求 - Send Post request to an external API using AWS Lambda in python 如何使用 Python 使用 JSON 文件正确执行 AWS Lambda API Post 请求 - How to properly do an AWS Lambda API Post Request with JSON file using Python 如何避免 AWS API 网关和 Lambda 超时? - How to avoid timeout from AWS API Gateway and Lambda? 如何从 AWS Lambda API 网关返回字节数组? - How to return byte array from AWS Lambda API gateway? 具有API网关集成的AWS Lambda-访问api名称和http请求的类型 - aws lambda with API gateway integration - accessing api name and type of http request Python request.headers与我在Chrome中看到的有所不同 - Python request.headers differs from what I see in Chrome 如何使用 Python 和 MySQL 向 AWS Lambda 发送 POST 请求 - How to send a POST request to AWS Lambda using Python and MySQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM