[PYTHON] Two-factor authentication with Cognito + Amplify (Enter ID / PW / "two-factor code value" on the login screen to authenticate)

Overview

Implementation

Amplify side

Sign in below.

Auth.signIn({"username": user_id, "password": user_password, "validationData": { "code": "WinAuth_code" }})
//* Code can be taken with Cognito's pre-authentication trigger

ʻAmplify.signIn ()` IF reference

Cognito side

The pre-authentication trigger is used to get the code of validationData and validate the code.

Pre-authentication trigger Lambda

import boto3

def lambda_handler(event, context):

    #Sample code to get the group associated with Username
    client = boto3.client('cognito-idp')
    response = client.admin_list_groups_for_user(UserPoolId=event['userPoolId'], Username=event['userName'] ) 

    print("---- ---- ---- ---- ---- ---- ---- ")
    print(event)
    print(response)
    print("---- ---- ---- ---- ---- ---- ---- ")

    #Execute code verification * Source omitted
    #Change the message depending on the error condition
    # ※
    #You can only change the message in case of an error (you can't change the HTTP status), so
    #If the code is incorrect, a dedicated message will be returned to the Amplify side.
    raise Exception("Cannot authenticate users from this user pool app client")  

    return event

Pre-authentication trigger Lambda log (contents of Lambda handler argument ʻevent`)

Pay attention to the following

{'callerContext': {'awsSdkVersion': 'aws-sdk-unknown-unknown',
                   'clientId': 'xxxxxxxxxxxxxxxxxxxxxxxxxx'},
 'region': 'ap-northeast-1',
 'request': {'userAttributes': {'cognito:token_nbf': '1582593027733',
                                'cognito:user_status': 'CONFIRMED',
                                'sub': '67eb1ed1-240b-4861-9844-f82ebc08d2f8'},
             'userNotFound': False,
             'validationData': {'aaaa': '12345'}},
 'response': {},
 'triggerSource': 'PreAuthentication_Authentication',
 'userName': 'hogehoge',
 'userPoolId': 'ap-northeast-1_xxxxxxxxx',
 'version': '1'}

Recommended Posts

Two-factor authentication with Cognito + Amplify (Enter ID / PW / "two-factor code value" on the login screen to authenticate)
Memo to get the value on the html-javascript side with jupyter
The story of trying to push SSH_AUTH_SOCK obsolete on screen with LD_PRELOAD