このチャプターの目次
APIが不特定のサービスから呼ばれたくない場合があります。
その場合に利用するのがIAM Authorizerです。
公式マニュアルは下記です。
IAMのポリシー定義
IAMに必要なポリシーは下記になります。
- execute-api:Invoke
- execute-api:manageConnections
IAMに強い権限をつけても良いのならばarn:aws:iam::aws:policy/AmazonAPIGatewayInvokeFullAccess
を設定することも可能です。
個別のポリシーならばIAMのポリシーに下記のような定義を追加してください。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke",
"execute-api:ManageConnections"
],
"Resource": "arn:aws:execute-api:リージョン:*:APIのID/パス"
}
]
}
呼び方
IAM認証のあるAPIをcurlなどで呼ぶのは手間です。
- Pythonの例
aws-requests-auth
をインストールしましょう。
pip install aws-requests-auth
API呼び方の例です。
import os
import requests
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
AWS_ACCESS_KEY_ID = '***************'
AWS_SECRET_ACCESS_KEY = '****************************'
os.environ['AWS_ACCESS_KEY_ID'] = AWS_ACCESS_KEY_ID
os.environ['AWS_SECRET_ACCESS_KEY'] = AWS_SECRET_ACCESS_KEY
def post():
region = "ap-northeast-1"
host = "******.execute-api.ap-northeast-1.amazonaws.com"
auth = BotoAWSRequestsAuth(
aws_host=host,
aws_region=region,
aws_service="execute-api",
)
stage = "api"
url = f"https://{host}/{stage}/*******"
response = requests.post(url, auth=auth, json=dict(foo="bar"))
return response.json()
if __name__ == "__main__":
print(post())
- Postmanの例
こちらのドキュメントを参照してください。