使用Swagger配置时API Gateway无Authorizer Lambda权限致500错误
Hey there, let's dig into this 500 error issue with your API Gateway + API Key authorizer setup via Swagger/CloudFormation. Since you've already checked the Lambda execution permission and compared Serverless-generated templates, let's focus on the most common gotchas that trip people up in this scenario:
1. Missing or Misconfigured Swagger Extensions for the Authorizer
Serverless automatically populates critical x-amazon-apigateway-authorizer extension fields that are easy to overlook when writing Swagger manually. Double-check these details:
- Ensure the
typeis set toTOKEN(for custom Lambda-based API key validation) - Verify
identitySourcepoints to the correct request location (e.g.,method.request.header.X-API-Keyif your key is passed in a header) - Confirm the
authorizerUriuses CloudFormation references (like!Subor!Ref) instead of hardcoded ARNs to avoid environment mismatches
Example of a properly configured Swagger authorizer block:
securityDefinitions: MyApiKeyAuthorizer: type: apiKey name: X-API-Key in: header x-amazon-apigateway-authorizer: type: TOKEN identitySource: method.request.header.X-API-Key authorizerUri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${YourLambdaFunctionArn}/invocations authorizerResultTtlInSeconds: 300
2. Broken Association Between Authorizer and API Methods
Even if your authorizer is defined correctly, you need to explicitly link it to protected endpoints in your Swagger:
- Add a
securityblock under each method that requires authorization, referencing your authorizer name:paths: /protected-endpoint: get: security: - MyApiKeyAuthorizer: [] x-amazon-apigateway-integration: # Your integration configuration here - Without this link, API Gateway won't trigger the authorizer for the method, which can lead to unexpected 500s if the method expects authorization metadata.
3. Invalid Lambda Authorizer Response Format
API Gateway has strict requirements for the JSON response from custom Lambda authorizers. A malformed response will throw a 500 instead of a 403/401. Make sure your Lambda returns a structure like this:
{ "principalId": "valid-api-key-user", "policyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:us-east-1:123456789012:abc123/*/GET/protected-endpoint" } ] } }
Check your Lambda's CloudWatch logs to confirm there are no syntax errors or missing fields in the response.
4. Overly Restrictive or Incorrect Lambda Permissions
While you've granted API Gateway permission to invoke the Lambda, double-check the SourceArn value in your permission policy. It must match the exact ARN pattern of your API Gateway:
LambdaInvokePermission: Type: AWS::Lambda::Permission Properties: FunctionName: !Ref YourLambdaFunction Action: lambda:InvokeFunction Principal: apigateway.amazonaws.com SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${YourApiId}/*/*/*
A mismatched SourceArn (e.g., hardcoded region/account ID) can silently block the invocation, leading to a 500 error.
5. Swagger Import Resource Mismatches
When importing Swagger into CloudFormation, ensure all resource references (like Lambda ARNs) use CloudFormation intrinsics (!Ref, !Sub) instead of hardcoded values. Hardcoded ARNs will break when deploying to different environments. Also, check your CloudFormation stack deployment logs for any failed resource creation events—sometimes the authorizer itself isn't provisioned correctly, causing method invocations to fail.
Quick Troubleshooting Tip
Enable detailed execution logging in API Gateway and check the logs for specific error messages. Phrases like "Invalid authorizer configuration" or "Lambda invocation failed" will point you directly to the root cause.
内容的提问来源于stack exchange,提问作者devrobf

