Python Cognito AccessTokenからUserAttributesを取得

Pythonスクリプトを使って、 Amazon Cognitoで作成したユーザープールの ユーザーに接続し AccessTokenからUserAttributesを取得する方法です。

Cognitoの ユーザープール側は、 [アプリケーションクライアント]の「認証フロー」で、 ALLOW_ADMIN_USER_PASSWORD_AUTHに チェックする必要があります。

認証のための管理 API のユーザー名パスワード認証
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.

Python ファイル書込み|追記

Pythonでファイルの書込みや追記などの処理を行いたい場合openTextIOWrapperを取得し書込み処理を行います

file_path_name = 'text_write.txt'
moji = """1行目:書きたい文字列
2行目:書きたい文字列
"""
with open(file_path_name, mode='w') as f:
    f.write(moji)

openのmode=’w’で書込みですが、ファイルが無い場合エラーになります。

従って書き込みたいファイルが存在しない場合mode=’x’を使います

file_path_name = 'text_write.txt'
moji = '1行目:書きたい文字列'
#ファイルを作って書き込む
with open(file_path_name, mode='x') as f: 
    f.write(moji)

ファイルが存在する場合、mode=’x’ではFileExistsErrorになります。

その場合、os.path.exists()などでファイルの存在を確認し‘x’/’w’を判断する。

import os
file_path_name = 'text_write.txt'
moji = '1行目:書きたい文字列'
#ファイルがあれば「ファイル書込み」それ以外は、「ファイル新規作成書込み」
write_mode = 'w' if os.path.exists(file_path_name) else 'x'
with open(file_path_name, mode=write_mode) as f: 
    f.write(moji)

ファイルに追記したい場合、mode=’a’を使います

import os
file_path_name = 'text_write.txt'
moji = '1行目:書きたい文字列'
#ファイルがあれば「ファイル追記」それ以外は、「ファイル新規作成書込み」
write_mode = 'a' if os.path.exists(file_path_name) else 'x'
with open(file_path_name, mode=write_mode) as f: 
    f.write(moji)

2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED