Pythonスクリプトを使って、 Amazon Cognitoで作成したユーザープールの ユーザーに接続し AccessTokenからUserAttributesを取得する方法です。
Cognitoの ユーザープール側は、 [アプリケーションクライアント]の「認証フロー」で、 ALLOW_ADMIN_USER_PASSWORD_AUTHに チェックする必要があります。
import boto3
config = {
"profile":None,
"pool_id": "プールID",
"client_id": "クライアントID",
"region": "リージョン"
}
try:
session = boto3.Session(profile_name=config['profile'])
# aws_access_key_id, aws_secret_access_keyを入れる場合↓
cognito = session.client('cognito-idp', region_name=config['region'])
res = cognito.admin_initiate_auth(
UserPoolId = config["pool_id"],
ClientId = config["client_id"],
AuthFlow = "ADMIN_USER_PASSWORD_AUTH",
AuthParameters = {
"USERNAME": "ユーザー名",
"PASSWORD": "パスワード",
}
)
user_info = cognito.get_user(AccessToken=res["AuthenticationResult"]["AccessToken"])
for info in user_info['UserAttributes']:
print(f"{info['Name']}:{info['Value']}")
except Exception as e:
print(e)
Cognito 設定画面[アプリケーションクライアント]の 認証フローで ALLOW_ADMIN_USER_PASSWORD_AUTHが 設定されていない場合、 下のInvalidParameterExceptionが 出ます
An error occurred (InvalidParameterException) when calling the AdminInitiateAuth operation: Auth flow not enabled for this client
ユーザー名もしくはパスワードが 間違えている場合 NotAuthorizedExceptionです
An error occurred (NotAuthorizedException) when calling the AdminInitiateAuth operation: Incorrect username or password.