为了实现在使用API Gateway时使用动态密钥,可以使用Lambda函数生成签名。以下是示例代码:
import json
import hmac
import hashlib
import base64
def lambda_handler(event, context):
http_method = event['httpMethod']
body = event['body'] if 'body' in event else ''
path = event['path']
headers = event['headers']
secret_key = 'YOUR-SECRET-KEY'
canonical_querystring = '&'.join(sorted(event['queryStringParameters'].items(), key=lambda x: x[0]))
canonical_headers = '\n'.join(f'{key.lower()}:{value}' for key, value in headers.items())
signed_headers = ';'.join(key.lower() for key in headers)
payload = '\n'.join([http_method, path, canonical_querystring, canonical_headers, signed_headers, body])
algorithm = hashlib.sha256
msg = payload.encode('utf-8')
signature = hmac.new(secret_key.encode('utf-8'), msg, algorithm).digest()
return {
'statusCode': 200,
'body': base64.b64encode(signature).decode('utf-8'),
'headers': {
'Content-Type': 'application/json'
}
}
该Lambda函数将接收API Gateway传来的HTTP请求事件,然后根据HTTP方法,路径,查询字符串,头和主体创建规范请求。该函数将使用您所提供的秘密密钥来生成签名。最后,该函数将返回一个包含签名的JSON响应。签名可以在API Gateway的“集成请求”页面中用作API密钥。