使用Lambda函数代替HTTP代理,该函数将对请求进行身份验证和跨域资源共享(CORS)设置。代码示例:
import json
import jwt
def lambda_handler(event, context):
# extract JWT token from Authorization header
auth_header = event['headers']['Authorization']
bearer_token = auth_header.split()[1]
decoded_token = jwt.decode(bearer_token, 'SECRET_KEY', algorithms=['HS256'])
# perform CORS settings
response = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": True,
"Access-Control-Allow-Methods": "OPTIONS,POST,GET",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token"
},
"body": json.dumps(decoded_token)
}
return response
此Lambda函数会解码JWT令牌并设置CORS响应头。该函数可以放置在API Gateway中的任何端点上。