1
0

More than 1 year has passed since last update.

Python3: Cognito から Access Token を取得

Last updated at Posted at 2022-02-19

AWS の Cognito から JWT Access Token を取得する方法です。
AuthFlow は ADMIN_USER_PASSWORD_AUTH です。
(以前は、ADMIN_NO_SRP_AUTH と呼ばれていました。)
次のページを参考にしました。
PythonでAWS Cognito認証

get_token.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	get_token.py
#
#					Feb/27/2022
#
# ------------------------------------------------------------------
import	sys
import	os
import	boto3
from dotenv import load_dotenv
# ------------------------------------------------------------------
def cognito_auth(parameter):
	# 認証開始
	try:
		aws_client = boto3.client('cognito-idp')

		aws_result = aws_client.admin_initiate_auth(
			UserPoolId = parameter["user_pool_id"],
			ClientId = parameter["user_pool_client_id"],
			AuthFlow = "ADMIN_USER_PASSWORD_AUTH",
#			AuthFlow = "USER_SRP_AUTH",
			AuthParameters = {
				"USERNAME": parameter["usr"],
				"PASSWORD": parameter["password"],
			}
		)

		# 認証完了
		sys.stderr.write("*** success ***\n")
		return aws_result

	except Exception as ee:
		# 認証失敗
		sys.stderr.write("*** error ***\n")
		sys.stderr.write(str(ee) + "\n")
#
		return None


# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
dotenv_path = '.env'
load_dotenv(dotenv_path)
parameter={}
parameter["user_pool_id"]=os.environ.get("USER_POOL_ID")
parameter["user_pool_client_id"]=os.environ.get("USER_POOL_CLIENT_ID")
parameter["usr"]=os.environ.get("USR")
parameter["password"]=os.environ.get("PASSWORD")
print(parameter["usr"])
print(parameter["password"])
result = cognito_auth(parameter)
print(result)
# print(result["AuthenticationResult"]["IdToken"])
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
.env
USER_POOL_ID="ap-northeast-1_510w*****"
USER_POOL_CLIENT_ID="818aso07e5pd8dj*******"
USR="aaa@example.com"
PASSWORD="secret123"
1
0
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
1
0