Home » #Technology » Implementing 2FA with TOTP (Time-Based One-Time Passwords)with Python

Implementing 2FA with TOTP (Time-Based One-Time Passwords)with Python

Two-Factor Authentication (2FA) has become a security standard, enhancing the protection of sensitive user data. Leveraging over 18 years of experience in the tech corporate world, I have consistently delivered innovative multiple solutions to requirements and led teams to enhance organizational tech performance. Drawing on this expertise, Among various 2FA methods, TOTP (Time-Based One-Time Passwords) stands out due to its simplicity and strong security model. This tech concept, provides a Python-centric walkthrough to help developers integrate TOTP-based 2FA into their applications.

What is TOTP?

TOTP is a time-sensitive one-time password based on a shared secret key and the current timestamp. It uses the HMAC-based One-Time Password (HOTP) algorithm and a moving factor (time). When paired with an authenticator app like Google Authenticator, users can generate secure, ephemeral codes.

Why Use TOTP for 2FA?

  • Enhanced Security: Adds a dynamic layer of protection to static passwords.
  • Convenience: Users can rely on widely-used authenticator apps.
  • No Internet Required: TOTP generation works offline, requiring no network connection.

Setting Up TOTP with Python

Here’s a step-by-step guide to implementing TOTP using Python.

Step 1: Install Required Libraries

To start, install the pyotp and qrcode libraries:

pip install pyotp qrcode
Step 2: Generate a Secret Key

A secret key forms the basis of TOTP. Here’s how to generate and share it with the user:

import pyotp

# Generate a base32 secret key
secret_key = pyotp.random_base32()
print(f"Your Secret Key: {secret_key}")

Output:

Your Secret Key: JBSWY3DPEHPK3PXP

Save this secret securely. The user will enter it into their authenticator app to generate TOTP codes.

Step 3: Create a Provisioning URL

To make it easier for users to add the secret key to their authenticator app, generate a QR code:

import qrcode

# Define app and user details
app_name = "MySecureApp"
user_email = "[email protected]"
provisioning_url = pyotp.totp.TOTP(secret_key).provisioning_uri(
    user_email, issuer_name=app_name
)

# Generate QR Code
qr = qrcode.make(provisioning_url)
qr.save("totp_qrcode.png")
print(f"Provisioning QR code generated: totp_qrcode.png")

This code creates a totp_qrcode.png file that the user can scan with their authenticator app.

Step 4: Validate TOTP Codes

Once the user sets up their authenticator app, validate the TOTP code they enter during login:

# Initialize the TOTP object with the secret key
totp = pyotp.TOTP(secret_key)

# Get a TOTP code from the user
user_code = input("Enter the TOTP code: ")

# Validate the TOTP code
if totp.verify(user_code):
    print("Authentication successful!")
else:
    print("Invalid TOTP code. Try again.")

Code Explanation

  • Secret Key: The shared secret between the app and the user.
  • Provisioning URI: A URL formatted to be compatible with most authenticator apps.
  • QR Code: A convenient way to transfer the secret to the authenticator app.
  • Verification: Validates the user’s TOTP code against the expected code.

Example: Putting It All Together

Here’s a complete implementation of TOTP-based 2FA in Python:

import pyotp
import qrcode

def generate_secret_key():
    return pyotp.random_base32()

def generate_qr_code(secret_key, app_name, user_email):
    provisioning_url = pyotp.totp.TOTP(secret_key).provisioning_uri(
        user_email, issuer_name=app_name
    )
    qr = qrcode.make(provisioning_url)
    qr.save("totp_qrcode.png")
    print("QR Code saved as totp_qrcode.png")
    return provisioning_url

def validate_totp(secret_key, user_code):
    totp = pyotp.TOTP(secret_key)
    return totp.verify(user_code)

if __name__ == "__main__":
    app_name = "MySecureApp"
    user_email = "[email protected]"
    
    # Step 1: Generate Secret Key
    secret_key = generate_secret_key()
    print(f"Secret Key: {secret_key}")
    
    # Step 2: Generate QR Code
    provisioning_url = generate_qr_code(secret_key, app_name, user_email)
    print(f"Provisioning URL: {provisioning_url}")
    
    # Step 3: Validate TOTP Code
    user_code = input("Enter the TOTP code from your authenticator app: ")
    if validate_totp(secret_key, user_code):
        print("Authentication successful!")
    else:
        print("Invalid code. Try again.")

Testing the Integration

  1. Run the script to generate a secret key and QR code.
  2. Scan the QR code with an authenticator app.
  3. Use the app to generate a TOTP code and input it into the program.
  4. Verify successful authentication.

Best Practices for Implementing TOTP

  1. Store Secrets Securely: Use encrypted databases or environment variables.
  2. Backup Codes: Provide users with backup codes in case they lose their device.
  3. Time Synchronization: Ensure your server’s clock is synchronized (e.g., with NTP).
  4. Rate Limiting: Prevent brute-force attacks by limiting failed login attempts.
  5. User Education: Inform users about setting up 2FA and its benefits.

My Tech Advice: Data is the foundation of every application, and 2FA plays a pivotal role in securing it in today’s tech development landscape. Implementing TOTP-based 2FA is a straightforward yet highly effective way to enhance your application’s security. With Python libraries like pyotp and qrcode, you can seamlessly integrate 2FA into your application, protecting user accounts from unauthorized access.

#AskDushyant
Note: The example and pseudo code is for illustration only. You must modify and experiment with the concept to meet your specific needs.
#TechConcept #TechAdvice #Authentication #2FA #TwoFactorAuthentication #TOTP

Leave a Reply

Your email address will not be published. Required fields are marked *