0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Python] Cognitoで認証周りを作る

Posted at

有効なユーザーにログインしてみる


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')

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?