在我為 Amazon API Gateway REST API 建立 AWS Lambda 授權器後,我收到 API 呼叫的「403 Forbidden」(403 禁止) 錯誤。
簡短描述
**注意:**此解決方案解決了與僅針對 REST API 設定的 Lambda 授權器相關的 403 錯誤。如需如何對其他 403 錯誤類型進行疑難排解的資訊,請參閱如何對 API Gateway 的 HTTP 403 錯誤進行疑難排解?
「403 Forbidden」(403 禁止) 錯誤可能是由以下原因造成的:
如果您 API 呼叫中的權杖或身分來源缺失、為空或未經驗證,那麼您會收到「401 Unauthorized」(401 未授權) 錯誤。如需詳細資訊,請參閱為什麼我在建立 Lambda 授權器後,收到 API 閘道「401 Unauthorized」(401 未授權) 錯誤?
解決方法
確認錯誤的原因
如果您尚未這麼做,請為您的 API Gateway REST API 開啟 CloudWatch Logs。如果您變更了授權器組態,請重新部署 API。
**注意:**如果您在執行 AWS Command Line Interface (AWS CLI) 命令時收到錯誤訊息,請參閱對 AWS CLI 錯誤進行疑難排解。此外,請確定您使用的是最新的 AWS CLI 版本。
查看錯誤日誌訊息
在 API Gateway 的回應中,尋找以下範例中的錯誤日誌訊息。
Lambda 授權器函式傳回帶有明確拒絕 IAM 政策文件時的錯誤日誌訊息範例:
{ "message": "User is not authorized to access this resource with an explicit deny"}
REST API 附加的資源政策隱含拒絕呼叫者存取時的錯誤日誌範例:
{ "message": "User is not authorized to access this resource"}
REST API 附加的資源政策明確拒絕呼叫者存取時的錯誤日誌範例:
{ "message": "User: anonymous is not authorized to perform: execute-api:Invoke on resource: <api-resource-arn> with an explicit deny"}
**注意:**有關 IAM 政策控制的 API 閘道 API 的詳細資訊,請參閱政策評估結果表。
查看 API 閘道日誌
若要查看授權工作流程,請查看 CloudWatch Logs 中的 API 閘道執行日誌。請注意 Lambda 授權器的輸出和 API 閘道資源政策評估的結果。在以下範例中尋找日誌錯誤訊息。
如果缺少所需權杖或與權杖驗證不相符,則錯誤日誌訊息範例如下:
Extended Request Id: EXAMPLEabcIdGxzR=Unauthorized request: request-id
**注意:**您日誌中的 Extended Request Id 值不同,是因為它是隨機產生的。
如果 Lambda 授權器傳回拒絕存取的政策,則錯誤日誌訊息範例如下:
Sending request to https://lambda.region.amazonaws.com/2015-03-31/functions/lambda-authorizer-arn/invocationsAuthorizer result body before parsing: {
"principalId": "user",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Deny",
"Resource": "resource-arn"
}
]
}
}
Using valid authorizer policy for principal: principal
Successfully completed authorizer execution
The client is not authorized to perform this operation.
**注意:**傳回的政策取決於您的 Lambda 授權器。如果傳回政策的 resource-arn 不包含請求資源,則該政策會隱含拒絕請求。
如果 API 閘道資源政策拒絕請求,則錯誤日誌訊息範例如下:
Extended Request Id: EXAMPLE1ABdGeZB=ExplicitDenyException User: anonymous is not authorized to perform: execute-api:Invoke on resource: api-resource-arn with an explicit deny: request-id
解決 Lambda 授權器的「not authorized to access this resource」(未獲授權存取此資源) 錯誤
由於政策快取,您可能會間歇性地收到「not authorized to access this resource」(無權存取此資源) 錯誤。若要確認已啟用授權快取,請查看 API 閘道主控台中的 Lambda 授權器設定。然後,執行下列其中一個動作:
若要確定授權器明確拒絕呼叫方存取的原因,請檢查 Lambda 授權器函式的程式碼。如果您確定問題是由於快取引起的,請更新程式碼以允許呼叫者存取。
如需說明,請參閱為什麼我的 API Gateway 代理資源 (具有已啟用快取的 Lambda 授權器) 會傳回 HTTP 403「User is not authorized to access this resource」(使用者無權存取此資源) 錯誤?
解決「not authorized to perform: execute-api:Invoke」(無權執行:execute-api:Invoke) 錯誤
若要確定您的 API 資源政策是否無效,或是否明確拒絕存取您的呼叫,請檢查您的 API 資源政策。您可以查看 API 執行日誌,以取得資源政策的回應結果。如需詳細資訊,請參閱 Amazon API Gateway 存取政策語言概觀和 Lambda 授權器和資源政策。
相關資訊
使用 API Gateway Lambda 授權器
控制和管理對 API Gateway 中 REST API 的存取權