Two-Factor Authentication (2FA) is a security measure that adds an extra layer of protection to user accounts. In this article, we will see how to implement a simple 2FA system in Python using pyotp to generate One-Time Passwords (OTP) and qrcode to generate a QR code that can be scanned by apps like Google Authenticator or Authy.
Requirements
Before getting started, make sure you have the following packages installed:
pip install pyotp qrcode[pil]
Generating an OTP Secret
For each user, you need to generate a shared secret to be used for OTP generation.
import pyotp
# Generate a random secret for the user
secret = pyotp.random_base32()
print("2FA Secret:", secret)
Generating a QR Code
The QR code can be scanned with an authentication app to easily set up 2FA.
import qrcode
# Create a TOTP object
totp = pyotp.TOTP(secret)
uri = totp.provisioning_uri(name="user@example.com", issuer_name="MyApp")
# Generate the QR code
qrcode.make(uri).save("qrcode_2fa.png")
print("QR code saved as qrcode_2fa.png")
Verifying the OTP
After the user has set up 2FA, they can provide an OTP to be verified during login.
# Entered by the user (from the authentication app)
otp_input = input("Enter the OTP code: ")
# Verify the OTP
if totp.verify(otp_input):
print("Correct code. Access granted.")
else:
print("Incorrect code. Access denied.")
Final Considerations
This implementation is a useful starting point for adding 2FA to your Python applications, especially in web or CLI apps. In a real-world application, you should store the 2FA secret securely and verify the code during the user authentication process.