本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
在本節中,您會了解使用 IAM 許可控制 API 存取權的許可模型。我們會顯示範本 IAM 政策聲明和政策聲明參考。政策聲明參考包括與 API 執行服務相關之 Action
與 Resource
欄位的格式。使用這些參考來建立您的 IAM 政策聲明。建立 IAM 政策聲明時,您可能需要考慮 API Gateway 資源政策影響授權工作流程的方式。如需詳細資訊,請參閱API Gateway 資源政策如何影響授權工作流程。
處理私有 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
是支援上述 Resource-path
之已部署 API METHOD_HTTP_VERB
Resource
執行個體的 URL 路徑預留位置。如需詳細資訊,請參閱在 API Gateway 中執行 API 之 IAM 政策的陳述式參考。
注意
若要讓 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 政策陳述式的動作與資源格式。
在 API Gateway 中執行 API 之許可的動作格式
API 執行 Action
表達式具有下列一般格式:
execute-api:
action
其中 action
是可用的 API 執行動作:
-
*,表示下列所有動作。
-
Invoke,在用戶端請求下用來呼叫 API。
-
InvalidateCache,在用戶端請求下用來使 API 快取失效。
在 API Gateway 中執行 API 之許可的資源格式
API 執行 Resource
表達式具有下列一般格式:
arn:aws:execute-api:
region
:account-id:api-id
/stage-name
/HTTP-VERB
/resource-path-specifier
其中:
-
region
是對應至 方法所部署 API AWS 的區域 (例如us-east-1
或*
所有 AWS 區域)。 -
account-id
是 REST API 擁有者的 12 位數 AWS 帳戶 ID。 -
api-id
是 API Gateway 分配給該方法之 API 的標識符。 -
stage-name
是與方法相關聯的階段名稱。 -
HTTP-VERB
是方法的 HTTP 動詞。它可以是下列其中一項:GET、POST、PUT、DELETE、PATCH。 -
resource-path-specifier
是所需方法的路徑
注意
如果您指定萬用字元 (*
),則 Resource
表達式會將萬用字元套用至表達式的其餘部分。
一些範例資源表達式包括:
-
arn:aws:execute-api:*:*:*
用於任何階段中的任何資源路徑, 用於任何 AWS 區域中的任何 API。 -
arn:aws:execute-api:us-east-1:*:*
適用於任何階段中的任何資源路徑,適用於 AWS 區域中的任何 APIus-east-1
。 -
arn:aws:execute-api:us-east-1:*:
對於任何階段中的任何資源路徑,對於 us-east-1 AWS 區域中具有api-id
/*api-id
識別符的 API。 -
arn:aws:execute-api:us-east-1:*:
,表示 us-east-1 的 AWS 區域中識別符為api-id
/test
/*api-id
之 APItest
階段的任何資源路徑。
如需進一步了解,請參閱 API Gateway Amazon Resource Name (ARN) 參考資料。