Skip to content

Instantly share code, notes, and snippets.

@mttjohnson
Created February 23, 2021 23:08
Show Gist options
  • Save mttjohnson/cf72cfe2bd127d401017e76718fde5d8 to your computer and use it in GitHub Desktop.
Save mttjohnson/cf72cfe2bd127d401017e76718fde5d8 to your computer and use it in GitHub Desktop.
Magento 2 TFA (Two-Factor Auth) usage from CLI
# Dependencies (oathtool, pwgen, python or python3)
yum install oathtool pwgen
MAGENTO_DOMAIN="xxxxxxxx_site_domain_xxxxxxxx" # example.lan
ADMIN_USER="xxxxxxxx_admin_username_xxxxxxxx" # example_admin
# Generate random secret for OTP use
SECRET=$(pwgen -1 -s -n 32)
# Detect Python version available - base32 encode and strip padding
TFA_SECRET=""
if command -v python3 >/dev/null 2>&1; then
TFA_SECRET=$(python3 -c "import base64; print(base64.b32encode(bytearray('${SECRET}', 'ascii')).decode('utf-8'))" | sed 's/=*$//')
else
TFA_SECRET=$(python -c "import base64; print base64.b32encode('${SECRET}')" | sed 's/=*$//')
fi
# Build otpauth URI
OTPAUTH_URL="otpauth://totp/${MAGENTO_DOMAIN}:${ADMIN_USER}?secret=${TFA_SECRET}&issuer=${MAGENTO_DOMAIN}&algorithm=SHA1&digits=6&period=30"
# Set Google TFA as the forced provider (OPTIONAL: if not already enabled)
bin/magento config:set twofactorauth/general/force_providers google
# Set the TFA secret for admin user
bin/magento security:tfa:google:set-secret "${ADMIN_USER}" "${TFA_SECRET}"
# Display secret value to save into 1Password OTP
echo "${TFA_SECRET}"
# Display OTP Auth URI which contains secret and can also be used in 1Password OTP
echo "${OTPAUTH_URL}"
# Generate OTP code from CLI using TFA Secret value
oathtool --time-step-size=30 --window=0 --totp=sha1 --base32 "${TFA_SECRET}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment