🐈

Cognito: 初期パスワードの変更が必要、かつ2段階認証が必要な場合の認証手順を確認する

2024/12/26に公開

なぜ

Cognitoのログインは InitiateAuth で始まり、初期パスワード変更や2段階認証などの追加の手順が必要な場合はRespondToAuthChallenge を呼び出すことでログイン処理が完了する。

初期パスワードの変更が必要、かつ2段階認証が必要な場合は RespondToAuthChallenge を繰り返し呼び出す必要があり、どちらを先に実行する必要があるのかを確認したい。

どう確認したか

事前準備

自身の環境に合わせて変数を定義

userPoolId=
clientId=
username=
temporaryPassword=
newPassword=
profile=

初期パスワードの変更が必要な状態にする

command

aws cognito-idp admin-set-user-password \
    --profile $profile \
    --user-pool-id $userPoolId \
    --username $username \
    --password $temporaryPassword

response

none

ログイン処理開始

InitiateAuth を実行

command

aws cognito-idp initiate-auth \
    --profile $profile \
    --auth-flow USER_PASSWORD_AUTH \
    --client-id $clientId \
    --auth-parameters "USERNAME=$username,PASSWORD=$temporaryPassword"

response

{
    "ChallengeName": "NEW_PASSWORD_REQUIRED",
    "Session": "xxxxx",
    "ChallengeParameters": {
        "USER_ID_FOR_SRP": "xxxxxxxx@local",
        "requiredAttributes": "[]",
        "userAttributes": "{\"email\":\"xxxxxxxx@local\"}"
    }
}

初期パスワード更新を先に求められる

RespondToAuthChallenge を実行

command

aws cognito-idp respond-to-auth-challenge \
    --profile $profile \
    --client-id $clientId \
    --challenge-name NEW_PASSWORD_REQUIRED \
    --session "xxxx" \
    --challenge-responses USERNAME=$username,NEW_PASSWORD=$newPassword

response

{
    "ChallengeName": "EMAIL_OTP",
    "Session": "xxxx",
    "ChallengeParameters": {
        "CODE_DELIVERY_DELIVERY_MEDIUM": "EMAIL",
        "CODE_DELIVERY_DESTINATION": "k***@g***"
    }
}

2段階認証を行う

再度 RespondToAuthChallenge を実行

command

aws cognito-idp respond-to-auth-challenge \
    --profile $profile \
    --client-id $clientId \
    --challenge-name EMAIL_OTP \
    --session "xxx" \
    --challenge-responses USERNAME=$username,EMAIL_OTP_CODE=<MFA_Code>

response

{
    "ChallengeParameters": {},
    "AuthenticationResult": {
        "AccessToken": "xxx",
        "ExpiresIn": 3600,
        "TokenType": "Bearer",
        "RefreshToken": "xxx",
        "IdToken": "xx"
    }
}

結果

NEW_PASSWORD_REQUIRED が先に返却されることがわかりました。

無事 IdToken を取得することができ、優勝。

Discussion