I started a blank serverless application project that uses AWS Lambda Annotations. It generated the following serverless.template
:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Transform": "AWS::Serverless-2016-10-31",
"Description": "An AWS Serverless Application. This template is partially managed by Amazon.Lambda.Annotations (v1.0.0.0).",
"Resources": {
"MyAppFunctionsGetGenerated": {
"Type": "AWS::Serverless::Function",
"Metadata": {
"Tool": "Amazon.Lambda.Annotations",
"SyncedEvents": [
"RootGet"
]
},
"Properties": {
"Runtime": "dotnet6",
"CodeUri": ".",
"MemorySize": 256,
"Timeout": 30,
"Policies": [
"AWSLambdaBasicExecutionRole"
],
"PackageType": "Zip",
"Handler": "MyApp::MyApp.Functions_Get_Generated::Get",
"Events": {
"RootGet": {
"Type": "Api",
"Properties": {
"Path": "/",
"Method": "GET"
}
}
}
}
}
},
"Outputs": {
"ApiURL": {
"Description": "API endpoint URL for Prod environment",
"Value": {
"Fn::Sub": "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
}
}
}
}
How and where should I put the configuration stuff to require API Keys? I tried different approaches I found here on SO but they don't work, they only work for the older approach without Annotations.
Answering my own question to be able to accept it later.
Since the Annotations approach generates a lot of stuff behind the scenes which is not directly accessible, including the API, you have to rely on Fn::Sub
to get the API Id you need to link to the usage plan.
Then, you can use the default Usage Plan, API Key, Usage Plan Key route.
Here is what I pieced together:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Transform": "AWS::Serverless-2016-10-31",
"Description": "An AWS Serverless Application. This template is partially managed by Amazon.Lambda.Annotations (v1.0.0.0).",
"Resources": {
"MyApiKey": {
"Type": "AWS::ApiGateway::ApiKey",
"Properties": {
"Enabled": true
}
},
"MyUsagePlan": {
"Type": "AWS::ApiGateway::UsagePlan",
"Properties": {
"ApiStages": [
{
"ApiId": { "Fn::Sub" : "${ServerlessRestApi}" },
"Stage": "Prod"
},
{
"ApiId": { "Fn::Sub" : "${ServerlessRestApi}" },
"Stage": "Stage"
}
]
}
},
"MyUsagePlanKey": {
"Type": "AWS::ApiGateway::UsagePlanKey",
"Properties": {
"KeyId": {
"Ref": "MyApiKey"
},
"KeyType": "API_KEY",
"UsagePlanId": {
"Ref": "MyUsagePlan"
}
}
},
"MyAppFunctionsGetGenerated": {
"Type": "AWS::Serverless::Function",
"Metadata": {
"Tool": "Amazon.Lambda.Annotations",
"SyncedEvents": [
"RootGet"
]
},
"Properties": {
"Runtime": "dotnet6",
"CodeUri": ".",
"MemorySize": 256,
"Timeout": 30,
"Policies": [
"AWSLambdaBasicExecutionRole"
],
"PackageType": "Zip",
"Handler": "MyApp::MyApp.Functions_Get_Generated::Get",
"Events": {
"RootGet": {
"Type": "Api",
"Properties": {
"Path": "/",
"Method": "GET",
"Auth": {
"ApiKeyRequired": true
}
}
}
}
}
}
},
"Outputs": {
"ApiURL": {
"Description": "API endpoint URL for Prod environment",
"Value": {
"Fn::Sub": "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
}
}
}
}