LoginSignup
2
5

More than 3 years have passed since last update.

Cognito+Amplifyで二要素認証する(ログイン画面で ID/PW/"二要素用のコード値" を入力して認証する)

Posted at

概要

  • Cognito+Amplifyで二要素認証する。
  • ログイン画面に ID/PW/コード値(二要素目扱い) の3項目を入力することを前提とする
    ※なので、二段階認証では無い・・・
  • codeにはGoogle Authenticator等で生成されるコード値が入る前提とする

実装

Amplify側

下記でサインインする。
※二要素目のパラメータとして validationData を送信する。

Auth.signIn({"username": user_id, "password": user_password, "validationData": { "code": "WinAuth_code" }})
// ※Cognitoの認証前トリガーでcodeがとれる

Amplify.signIn() のIF参照

Amplify.signIn() の第1パラメータを SignInOpts 形式で指定している

Cognito側

認証前トリガーを使って、validationDatacode を取得し、コードの検証をする形になる。

認証前トリガーのLambda

import boto3

def lambda_handler(event, context):

    # 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("---- ---- ---- ---- ---- ---- ---- ")

    # コード検証を実行 ※ソースは省略
    # エラーの条件によってメッセージを変える
    # ※
    # エラー時にメッセージを変更することしかできない(HTTPのステータスを変えるとかは出来ない)ので、
    # コードが誤っている場合は専用のメッセージをAmplify側に返すことになる
    raise Exception("Cannot authenticate users from this user pool app client")  

    return event

認証前トリガーLambdaのログ(Lambdaハンドラ引数の event の中身)

下記に注目

  • event['username']に入力したユーザネームが来ている
  • event['request']['validationData'] が来ている
{'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'}
2
5
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
2
5