Skip to content

Instantly share code, notes, and snippets.

@gellweiler
Last active July 31, 2021 14:41
Show Gist options
  • Save gellweiler/ebc66335da18dbf1ecf166fdaf6add1d to your computer and use it in GitHub Desktop.
Save gellweiler/ebc66335da18dbf1ecf166fdaf6add1d to your computer and use it in GitHub Desktop.
Setup TOTP authentication for an aws cognito user.

This shell script will guide you through setting up TOTP authentiaction for an aws cognito user. It generates a qr code that can be scanned by a TOTP authenticator app.

Requirements:

  • Aws-Cli
  • jq
  • qrencode
#!/bin/bash
# Script to setup totp for an aws cognito user.
set -eu -o pipefail
export AWS_ACCESS_KEY_ID=XXX
export AWS_SECRET_ACCESS_KEY=XXX
export AWS_DEFAULT_REGION=XXX
# You need a client id without a secret code for this to work.
# See: https://stackoverflow.com/a/51174402
export CLIENT_ID='XXX'
# This will be displayed in the totp app.
export ISSUER='MyApp'
echo -n "Username: "
read -r username
echo ""
echo -n "Password: "
read -r -s password
echo ""
echo "[INFO] retrieving access token"
access_token="$(aws cognito-idp initiate-auth --auth-flow USER_PASSWORD_AUTH --client-id "$CLIENT_ID" --auth-parameters "USERNAME=$username,PASSWORD=$password" | jq -r .AuthenticationResult.AccessToken)"
echo "[INFO] generating secet code"
secret_code="$(aws cognito-idp associate-software-token --access-token "$access_token" | jq -r .SecretCode)"
echo "[INFO] generating qr code. Please scan the code with your totp app"
qr_code_data="otpauth://totp/$username?secret=$secret_code&issuer=$ISSUER"
echo -n $qr_code_data | qrencode -t ansiutf8
echo -n "Choose a device name: "
read devicename
echo ""
echo -n "Enter the current TOTP-Code: "
read totp
echo ""
echo "[INFO] configuring device"
aws cognito-idp verify-software-token --access-token "$access_token" --user-code "$totp" --friendly-device-name $devicename
echo "[INFO] setting t2f preference"
aws cognito-idp set-user-mfa-preference --software-token-mfa-settings Enabled=true,PreferredMfa=true --access-token "$access_token"
echo "[INFO] all done, you should now be forced to enter a totp code when logging in"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment