针对调用 API 的访问控制
在本节中,您将了解如何编写 IAM 策略语句,以控制谁可以调用 API Gateway 中部署的 API。在这里,您还将找到策略语句参考,包括与 API 执行服务有关的 Action
和 Resource
字段的格式。您还应该研究API Gateway 资源策略如何影响授权工作流程中的 IAM 部分。
对于私有 API,您应使用 API Gateway 资源策略和 VPC 终端节点策略的组合。有关更多信息,请参阅以下主题:
控制谁可以使用 IAM 策略调用 API Gateway API 方法
要控制谁可以或不可以使用 IAM 权限调用已部署的 API,请创建一个包含必要权限的 IAM 策略文档。此类策略文档的模板如下所示。
{ "Version": "2012-10-17", "Statement": [ { "Effect": "
Permission
", "Action": [ "execute-api:Execution-operation
" ], "Resource": [ "arn:aws:execute-api:region
:account-id
:api-id
/stage
/METHOD_HTTP_VERB
/Resource-path
" ] } ] }
此处,
将被替换为 Permission
Allow
或 Deny
,具体取决于您是要授予或撤消相应权限。
将被替换为受 API 执行服务支持的操作。Execution-operation
表示受指定资源支持的 HTTP 动词。METHOD_HTTP_VERB
是已部署的 API Resource-path
Resource
实例的 URL 路径占位符,该实例可支持上述的
。有关更多信息,请参阅在 API Gateway 中执行 API 的 IAM 策略的语句参考。METHOD_HTTP_VERB
注意
要使 IAM 策略生效,您必须已通过将该方法的 authorizationType
属性设置为 AWS_IAM
对 API 方法启用 IAM 身份验证。否则,这些 API 方法会从外部进行访问。
例如,要授予某个用户查看特定 API 提供的宠物列表的权限,同时拒绝该用户向列表添加宠物的权限,您可以在 IAM 策略中包含以下语句:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:
account-id
:api-id
/*
/GET/pets
" ] }, { "Effect": "Deny", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:account-id
:api-id
/*
/POST/pets
" ] } ] }
要授予某个用户查看配置为 GET /pets/
的 API 提供的某个特定宠物的权限,您可以在 IAM 策略中包含以下语句:{petId}
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:us-east-1:
account-id
:api-id
/*/GET/pets
/a1b2
" ] } ] }
在 API Gateway 中执行 API 的 IAM 策略的语句参考
以下信息将介绍用于执行 API 的访问权限的 IAM 策略语句的 Action 和 Resource 格式。
在 API Gateway 中执行 API 的权限的 Action 格式
API 执行的 Action
表达式有以下一般格式:
execute-api:
action
其中 action
是一项可用的 API 执行操作:
-
*,代表以下所有操作。
-
Invoke (调用),用于根据客户端请求调用 API。
-
InvalidateCache,用于根据客户端请求使 API 缓存失效。
在 API Gateway 中执行 API 的权限的 Resource 格式
API 执行的 Resource
表达式有以下一般格式:
arn:aws:execute-api:
region
:account-id:api-id
/stage-name
/HTTP-VERB
/resource-path-specifier
其中:
-
region
为 Amazon 区域(例如,适用于所有us-east-1
区域的*
或 Amazon),与该方法已部署的 API 相对应。 -
account-id
是 REST API 所有者的 12 位 Amazon 账户 ID。 -
api-id
是 API Gateway 为该方法分配给 API 的标识符。 -
stage-name
是与方法关联的阶段的名称。 -
HTTP-VERB
是该方法的 HTTP 动词。它可以是以下任一动词:GET、POST、PUT、DELETE、PATCH。 -
resource-path-specifier
是前往预期方法的路径。
一些示例资源表达式包括:
-
arn:aws:execute-api:*:*:*
,适用于任何 Amazon 区域内任何 API 的任何阶段中的任何资源路径。 -
arn:aws:execute-api:us-east-1:*:*
,适用于us-east-1
的任何 Amazon 区域内任何 API 的任何阶段中的任何资源路径。 -
arn:aws:execute-api:us-east-1:*:
,适用于Amazon区域 us-east-1 内带api-id
/*api-id
标识符的 API 中任何阶段的任何资源路径。 -
arn:aws:execute-api:us-east-1:*:
,适用于Amazon区域 us-east-1 内带api-id
/test
/*api-id
标识符的 API 中test
阶段的资源路径。
要了解更多信息,请参阅 API Gateway Amazon 资源名称 (ARN) 参考。