Tutorial: Adding Two-Factor Authentication to Flask AI Web Services

Implementing two-factor authentication (2FA) enhances the security of your Flask AI web services by requiring users to verify their identity through a second method beyond just a password. This tutorial guides you through integrating 2FA into your Flask application using popular libraries and best practices.

Prerequisites

  • Basic knowledge of Flask framework
  • Python 3.6+ installed
  • Flask and Flask extensions installed
  • Understanding of user authentication concepts

Installing Necessary Libraries

  • Flask
  • PyOTP for generating OTPs
  • Flask-Login for user session management
  • Flask-Mail for sending verification codes (optional)

Run the following command to install the required libraries:

pip install Flask Flask-Login PyOTP Flask-Mail

Setting Up Flask Application

Create a basic Flask app with user login functionality. Define user management and session handling.

Sample code snippet:

from flask import Flask, render_template, redirect, url_for, request, flash

from flask_login import LoginManager, login_user, login_required, logout_user, UserMixin

app = Flask(__name__)

app.secret_key = ‘your_secret_key’

login_manager = LoginManager()

login_manager.init_app(app)

class User(UserMixin):

def __init__(self, id):

self.id = id

@login_manager.user_loader

def load_user(user_id):

return User(user_id)

Implementing Two-Factor Authentication

Generating and Storing OTP Secret

When a user enables 2FA, generate a secret key and store it securely in your database.

Example:

import pyotp

user.secret = pyotp.random_base32()

Verifying OTP During Login

After user enters credentials, prompt for OTP. Verify using PyOTP:

otp = request.form[‘otp’]

totp = pyotp.TOTP(user.secret)

if totp.verify(otp):

login_user(user)

return redirect(url_for(‘dashboard’))

else:

flash(‘Invalid OTP’)

Enabling Users to Set Up 2FA

Provide an interface for users to scan a QR code with authenticator apps or manually enter the secret.

Generate QR code:

import qrcode

uri = totp.provisioning_uri(name=user.email, issuer_name=’YourAppName’)

img = qrcode.make(uri)

Display the QR code image to the user for scanning.

Best Practices and Security Tips

  • Store secrets securely, encrypted if possible.
  • Allow users to reset or disable 2FA.
  • Implement rate limiting to prevent brute-force OTP attacks.
  • Encourage users to use authenticator apps like Google Authenticator or Authy.

Adding 2FA significantly improves your web service’s security. Regularly update your implementation to adhere to the latest security standards and user privacy considerations.