You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在AWS Lambda中验证x-api-key的方法

Lambda中验证请求体里的X-API-Key方案

核心思路

从Lambda触发事件中提取请求体内的x-api-key字段,通过AWS SDK调用API Gateway管理接口验证该密钥的有效性,根据验证结果决定是否执行业务逻辑。


1. 提取请求体中的API密钥

Lambda事件的body字段包含请求体内容,先解析为JSON对象后取出目标密钥:

import json

def lambda_handler(event, context):
    # 解析请求体
    try:
        request_body = json.loads(event['body'])
        api_key = request_body.get('x-api-key')
        if not api_key:
            return {
                'statusCode': 400,
                'body': json.dumps({'message': 'X-API-Key is required in request body'})
            }
    except json.JSONDecodeError:
        return {
            'statusCode': 400,
            'body': json.dumps({'message': 'Invalid request body format'})
        }

2. 配置Lambda权限

给Lambda执行角色添加apigateway:GetApiKey权限,允许其调用API Gateway的密钥验证接口。示例IAM策略:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "apigateway:GetApiKey",
            "Resource": "arn:aws:apigateway:<你的AWS区域>::/apikeys/*"
        }
    ]
}

3. 验证API密钥有效性

使用AWS SDK调用get_api_key接口,通过传入的密钥值匹配并检查是否启用:

import boto3

# 初始化API Gateway客户端
apigw_client = boto3.client('apigateway', region_name='<你的AWS区域>')

def validate_api_key(api_key):
    try:
        # 通过密钥值查询详情,需开启includeValue
        response = apigw_client.get_api_key(
            value=api_key,
            includeValue=True
        )
        # 检查密钥是否启用
        return response.get('enabled', False)
    except apigw_client.exceptions.NotFoundException:
        # 密钥不存在
        return False
    except Exception as e:
        print(f"API密钥验证失败: {str(e)}")
        return False

4. 处理验证结果

在Lambda主函数中调用验证逻辑,根据结果返回对应响应:

def lambda_handler(event, context):
    # (前面的请求体解析代码)
    
    # 验证密钥
    if not validate_api_key(api_key):
        return {
            'statusCode': 403,
            'body': json.dumps({'message': 'Invalid or disabled X-API-Key'})
        }
    
    # 验证通过,执行业务逻辑
    return {
        'statusCode': 200,
        'body': json.dumps({'message': 'Request authorized'})
    }

内容的提问来源于stack exchange,提问作者Lovasz Kristof

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:32:45