import boto3
import os
import hashlib
import hmac
import base64
# hash化する関数
def get_hash(username):
secret_key = os.getenv('SECRET_CLIENT')
msg=username + os.getenv('CLIENT_ID')
dig = hmac.new(str(secret_key).encode('utf-8'),
msg=str(msg).encode('utf-8'), digestmod=hashlib.sha256).digest()
d2 = base64.b64encode(dig).decode()
dig = d2
return dig
def login(username, password):
CLIENT_ID = os.getenv('CLIENT_ID')
cognito_client = boto3.client('cognito-idp')
auth_response = cognito_client.initiate_auth(
ClientId=CLIENT_ID,
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password,
'SECRET_HASH': get_hash(username),
}
)
if auth_response['AuthenticationResult']:
access_token = auth_response['AuthenticationResult']['AccessToken']
refresh_token = auth_response['AuthenticationResult']['RefreshToken']
return{
"access_token": access_token,
"refresh_token": refresh_token
}
else:
raise ValueError("Login Failed")
login('username', 'password')