如何在SAM中为API方法启用ApiKeyRequired属性?
在SAM中配置API Gateway标准API Keys验证的解决方案
我来帮你梳理问题并给出可行的配置方案——你遇到的Swagger配置不生效,主要是因为几个关键环节没配置到位,结合SAM的特性,我们可以通过两种方式实现API Key验证:
一、直接通过SAM资源配置(无需Swagger)
这是最简单的方式,不用修改Swagger,直接在SAM的AWS::Serverless::Api或单个API事件中配置:
1. 全局开启API Key验证
如果希望整个API的所有方法都要求API Key:
MyApi: Type: AWS::Serverless::Api Properties: StageName: prod Auth: ApiKeyRequired: true # 全局启用API Key验证 UsagePlan: CreateUsagePlan: PER_API # 自动创建与API绑定的使用计划 Description: "API访问使用计划" Quota: Limit: 1000 Period: MONTH Throttle: BurstLimit: 100 RateLimit: 50
2. 针对单个方法开启API Key验证
如果只需要特定方法验证API Key,可以在Lambda的事件配置中单独设置:
MyLambdaFunction: Type: AWS::Serverless::Function Properties: CodeUri: ./src Handler: index.handler Runtime: nodejs18.x Events: GetMachine: Type: Api Properties: RestApiId: !Ref MyApi Path: /machines/{resourceid} Method: get Auth: ApiKeyRequired: true # 仅该方法启用API Key验证
二、修正Swagger配置并结合SAM资源
如果你坚持用Swagger定义API,需要修正配置中的几个问题,同时补充SAM的关联资源:
1. 修正后的Swagger配置
你的原配置中,security和securityDefinitions的关联是对的,但缺少了API Key来源声明,同时建议把名称改得更清晰:
swagger: "2.0" info: title: !Ref AWS::StackName paths: "/machines/{resourceid}": get: parameters: - name: resourceid in: path type: string required: true x-amazon-apigateway-integration: httpMethod: POST type: aws_proxy uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambda.Arn}/invocations responses: {} security: - ApiKeyAuth: [] # 与下方securityDefinitions的名称对应 securityDefinitions: ApiKeyAuth: type: apiKey name: x-api-key # API Gateway默认的API Key请求头,若想用Authorization也可修改 in: header x-amazon-apigateway-api-key-source: HEADER # 明确指定API Key从请求头获取
2. 在SAM中关联Swagger并配置资源
需要把Swagger关联到Api资源,同时创建API Key并绑定到使用计划:
MyApi: Type: AWS::Serverless::Api Properties: StageName: prod DefinitionBody: !Ref MySwagger # 引用你的Swagger定义 Auth: UsagePlan: CreateUsagePlan: PER_API # 创建API Key MyApiKey: Type: AWS::ApiGateway::ApiKey Properties: Name: "MachineApiKey" Enabled: true StageKeys: - RestApiId: !Ref MyApi StageName: prod # 将API Key绑定到使用计划 MyUsagePlanKey: Type: AWS::ApiGateway::UsagePlanKey Properties: KeyId: !Ref MyApiKey KeyType: API_KEY UsagePlanId: !Ref MyApi.UsagePlanId # SAM自动生成的使用计划ID
为什么你的原配置不生效?
- 缺少
x-amazon-apigateway-api-key-source: HEADER声明,API Gateway无法识别从哪里获取API Key; - 没有创建API Key并绑定到使用计划——即使开启了验证,没有有效的Key也无法通过;
- 若你用
Authorization作为API Key的请求头,需要确保API Gateway的API Key验证逻辑能识别这个头(默认是x-api-key,修改后需要对应)。
内容的提问来源于stack exchange,提问作者user3492652




