5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

IAM認証のAPI Gatewayを叩く。SigV4署名ヘッダーを作成(python)

Last updated at Posted at 2020-06-17

#IAM認証のAPI Gatewayを実行する(python)
curl等でAPIの結果を返したいとき、HTTPリクエストのヘッダ(SigV4署名)を算出する必要があるが、資料が見当たらないため備忘
APIGatewayをIAM認証にする方法はほかのサイト参照。
ハッシュ値を算出する方法があるがよくわからないので、必要になったときにbotocoreのライブラリ内を見て作成する。

check_iam.py
import os
from botocore.awsrequest import AWSRequest
from botocore.auth import SigV4Auth
from botocore.endpoint import URLLib3Session
from botocore.credentials import Credentials
import requests

url_ = "https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/v1"
### 1. Credential生成  
credentials = Credentials(os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_ACCESS_KEY'])

### 2. AWSRequest生成
request = AWSRequest(method="GET", url=url_)

### 3. AWSリクエスト署名
SigV4Auth(credentials, 'execute-api', ap-northeast-1).add_auth(request)

### 4. API発行
headers = {
    'Authorization': request.headers['Authorization'],
    'Host':'xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com',
    'X-Amz-Date':request.context['timestamp']
}

response = requests.get(url_,headers=headers)

print(response.text)
5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?