I'm trying to create an API Gateway which invokes a Lambda function using SAM. I want to restrict access to the API in such a way that only certain IAM accounts/users can access the API. How should I do that? I couldn't find a proper way to attach a resource access policy to an API endpoint in SAM.
-
I think what you want is in your `AWS::Serverless::Function` resource, you want to assign a `Role`, which will be an IAM user with the proper permissions. https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction – HolyMoly Mar 19 '19 at 22:29
2 Answers
You can specify an AWS::Serverless::Api resource in your SAM template that is configured with an Auth object which in turn should have AWS_IAM
as DefaultAuthorizer
. In other words, something like:
Resources:
ApiWithIamAuth:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: AWS_IAM
Next, you need to create a policy for your users so that they can invoke the API. Control Access for Invoking an API provides the reference, IAM Policy Examples for API Execution Permissions contains two examples
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:*:a123456789/test/POST/mydemoresource/*"
]
}
]
}
and finally Create and Attach a Policy to an IAM User lists the manual steps to associate the policy with an IAM user, an IAM role or an IAM group.

- 32,104
- 16
- 121
- 156
Generally, you can limit the access to your APIs using IAM roles.
However, SAM supports only a limited number of resource types, so you have to use the IAM Policy type of CloudFormation instead.
Since SAM is only a higher-level abstraction of CloudFormation, it is no problem to use native CloudFormation resource types in your SAM template: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/appendix-appendix-sam-templates-and-cf-templates.html

- 503
- 1
- 6
- 18