DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Two-Factor Authentication Guide

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Two-Factor Authentication Guide

Why 2FA Matters

Passwords alone are insufficient. Data breaches expose billions of credentials annually, phishing campaigns trick users into revealing their passwords, and credential stuffing attacks automate login attempts across services. Two-factor authentication (2FA) adds a second layer of verification that renders stolen passwords useless.

2FA Factor Types

| Factor | Examples | Security Level | |--------|----------|----------------| | Knowledge | Password, PIN | Weak | | Possession | Phone, hardware key, authenticator app | Strong | | Inherence | Fingerprint, face scan | Strong | | Location | GPS, IP range | Moderate | | Time | One-time codes | Moderate |

Strong 2FA combines something you know (password) with something you have (phone or key).

TOTP (Time-Based One-Time Password)

TOTP is the most widely implemented 2FA method. The client and server share a secret key, and both derive the same 6-8 digit code from the current time.

Server-Side Implementation

import pyotp

import base64

import os

class TOTPManager:

def init(self):

self.issuer = "MyApp"

def generate_secret(self):

"""Generate a new TOTP secret."""

return pyotp.random_base32()

def get_provisioning_uri(self, username, secret):

"""Generate URI for QR code."""

return pyotp.totp.TOTP(secret).provisioning_uri(

name=username,

issuer_name=self.issuer

)

def verify_code(self, secret, code):

"""Verify a TOTP code with a 1-step window for clock drift."""

totp = pyotp.TOTP(secret)

return totp.verify(code, valid_window=1)

Displaying the QR Code

import qrcode

import qrcode.image.svg

def render_qr(uri):

img = qrcode.make(uri, image_factory=qrcode.image.svg.SvgImage)

return img.to_string().decode()

Client-Side Setup

// Generate QR in the browser

const secret = await generateTOTPSecret();

const uri = `otpauth://to


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)