This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.
MFA Implementation
MFA Implementation
MFA Implementation
MFA Implementation
MFA Implementation
MFA Implementation
MFA Implementation
MFA Implementation
MFA Implementation
MFA Fundamentals
Multi-factor authentication requires two or more factors: something you know (password), something you have (phone), or something you are (biometric).
TOTP Implementation
Time-based One-Time Passwords (TOTP) are the most widely deployed MFA method:
import pyotp
import qrcode
import io
import base64
class TOTPManager:
def init(self, issuer="Example Corp"):
self.issuer = issuer
def generate_secret(self):
return pyotp.random_base32()
def get_provisioning_uri(self, email, secret):
totp = pyotp.TOTP(secret)
return totp.provisioning_uri(name=email, issuer_name=self.issuer)
def generate_qr(self, email, secret):
uri = self.get_provisioning_uri(email, secret)
qr = qrcode.make(uri)
buf = io.BytesIO()
qr.save(buf, format="PNG")
return base64.b64encode(buf.getvalue()).decode()
def verify_code(self, secret, code):
totp = pyotp.TOTP(secret)
Allow 1 step before/after for clock drift
return totp.verify(code, valid_window=1)
def get_current_code(self, secret):
totp = pyotp.TOTP(secret)
return totp.now()
SMS-Based MFA
import random
import string
class SMSMFAManager:
def init(self, sms_provider):
self.sms_provider = sms_provider
self.codes = {} # phone -> {code, expires_at}
def send_code(self, phone):
code = ''.join(random.choices(string.digits, k=6))
expiry = datetime.utcnow() + timedelta(minutes=5)
self.codes[phone] = {"code": code, "expires_at": expiry}
self.sms_provider.send(phone, f"Your code is: {code}")
return True
def verify_code(self, phone, code):
stored = self.codes.get(phone)
Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.
Found this useful? Check out more developer guides and tool comparisons on AI Study Room.
Top comments (0)