
こんな悩みを解決できる記事を書きました!
僕は現役フリーランスエンジニア(歴9年)で、資格は13個保有しています。
結論、CognitoのID Poolを使ってAPI GatewayのIAM認証を突破するのは非常に簡単です。
具体的なソースコードも載せているので安心してくださいね。


本記事を読めば、ID PoolでAPI GatewayのIAM認証を突破する方法が理解できるので早速見ていきましょう。



すぐ読み終わるので、ぜひ最後まで読んでくださいね♪
ID PoolでAPI GatewayのIAM認証を突破する方法
早速ですが、CognitoのID PoolでAPI GatewayのIAM認証を突破する方法を解説します。
Chaliceの設定
まずは環境を準備します。
今回はChaliceを使いますが、API GatewayにIAM認証付きのAPIがあればOKです。





↑のような感じですね。
Chaliceのソースコードは後ほど載せておきます。


IDプールの作成
IAM認証を通過するには権限が必要です。
今回は、CognitoのIDプールを利用して一時的な権限を払い出します。


IDプールの管理をクリックします。


新しいIDプールの作成をクリックします。




IDプール名を入力し、プールの作成をクリックします。



認証されていないIDに必ずチェックを入れてください。


ロールを編集し、許可をクリックします。
ロールの内容は以下になります。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"*"
]
}
]
}
API Gatewayの認証を突破するための権限が必要なので「execute-api:Invoke」を記載します。



Resouceは面倒くさいので全てにしていますが、限定的にするのをおすすめします。


IDプールのIDはソースコード内で使用するのでコピーします。
Pythonのソースコードはこちら
Pythonのソースコードは以下になります。
from chalice import Chalice, IAMAuthorizer
from botocore.awsrequest import AWSRequest
from botocore.auth import SigV4Auth
import boto3
import json
import requests
app = Chalice(app_name='hello-world')
authorizer = IAMAuthorizer()
@app.route('/', methods=['GET'], authorizer=authorizer)
def index():
return {'hello': 'world'}
@app.route('/hoge', methods=['GET'])
def hoge():
REGION = 'ap-northeast-1'
ARN_ID_POOL = 'ap-northeast-1:...'
client = boto3.client('cognito-identity', REGION)
credentials_for_identity = client.get_credentials_for_identity(
IdentityId=client.get_id(IdentityPoolId=ARN_ID_POOL)['IdentityId']
)
session = boto3.session.Session(
aws_access_key_id=credentials_for_identity['Credentials']['AccessKeyId'],
aws_secret_access_key=credentials_for_identity['Credentials']['SecretKey'],
aws_session_token=credentials_for_identity['Credentials']['SessionToken'],
region_name=REGION
)
url = 'https://....execute-api.ap-northeast-1.amazonaws.com/api/'
credentials = session.get_credentials()
request = AWSRequest(method = "GET", url = url)
SigV4Auth(credentials, 'execute-api', REGION).add_auth(request)
res = requests.get(
url,
headers = {
'Authorization': request.headers['Authorization'],
'X-Amz-Date': request.context['timestamp'],
'X-Amz-Security-Token': credentials_for_identity['Credentials']['SessionToken']
}
)
return res.json()
「/」のAPIを「/hoge」から実行しています。



意外と簡単ですよね?
難しいのはIAMロールの権限周りでしたね。
よくある質問
署名バージョン4の公式ドキュメントはありますか?
下記になります。
CognitoIdentityのドキュメントはありますか?
下記になります。
まとめ
今回は、ID PoolでAPI GatewayのIAM認証を突破する方法について解説しました。
以下が本記事のまとめになります。



最後までお読みいただき、ありがとうございました!
- クソおすすめ本



海外のエンジニアがどういった思考で働いているかが理解できます。
海外に行く気はないけど海外エンジニアの動向が気になる雑魚エンジニアにおすすめです(本当におすすめな本しか紹介しないのでご安心を)。