MFA & Passwordless

🔥 Vibe Prompt

"Implement TOTP MFA, WebAuthn passkeys, and risk-based authentication."

TOTP (Time-based One-Time Password)

import pyotp
import qrcode

# Generate secret
secret = pyotp.random_base32()
print(f"Secret: {secret}")

# Create provisioning URI (for QR code)
totp = pyotp.TOTP(secret)
uri = totp.provisioning_uri(name="alice@example.com", issuer_name="MyApp")
print(f"QR URI: {uri}")

# Generate QR code
qr = qrcode.make(uri)
qr.save("totp_qr.png")

# Verify
code = input("Enter TOTP code: ")
if totp.verify(code):
    print("✅ TOTP valid!")
else:
    print("❌ Invalid code")

# Verify with drift tolerance (30s window)
if totp.verify(code, valid_window=1):
    print("✅ Valid within 30s window")

WebAuthn / Passkeys

// Registration (browser)
const credential = await navigator.credentials.create({
  publicKey: {
    challenge: new Uint8Array([...]),  // From server
    rp: { name: "MyApp", id: "example.com" },
    user: {
      id: new Uint8Array([1,2,3]),
      name: "alice@example.com",
      displayName: "Alice"
    },
    pubKeyCredParams: [{ type: "public-key", alg: -7 }],  // ES256
    authenticatorSelection: {
      authenticatorAttachment: "platform",  // Built-in (Touch ID, Face ID)
      residentKey: "required",  // Discoverable credential
      userVerification: "required"
    }
  }
});

// Authentication
const assertion = await navigator.credentials.get({
  publicKey: {
    challenge: new Uint8Array([...]),  // From server
    rpId: "example.com",
    allowCredentials: [{type: "public-key", id: credentialId}],
    userVerification: "required"
  }
});

Risk-Based Authentication (RBA)

def calculate_risk(user, request):
    score = 0
    
    # Location
    if request.geo.country != user.known_countries:
        score += 30
    
    # Device
    if request.user_agent not in user.known_devices:
        score += 20
    
    # Time
    if 2 <= datetime.now().hour <= 5:  # 2-5 AM
        score += 15
    
    # IP reputation
    if is_vpn_or_tor(request.ip):
        score += 25
    
    # Failed attempts
    if user.failed_logins_last_hour > 3:
        score += 10
    
    # Decision
    if score > 70:
        return "BLOCK"
    elif score > 40:
        return "CHALLENGE_MFA"  # Require MFA
    else:
        return "ALLOW"

MFA Methods Comparison

| Method | UX | Security | Phishing Resistant | |--------|-----|----------|--------------------| | TOTP (Google Auth) | Medium | High | No | | SMS (SMS OTP) | Good | Low | No | | Push (Duo) | Good | High | No | | WebAuthn/Passkeys | Best | Highest | Yes | | Security Key (FIDO2) | Medium | Highest | Yes |

Best Practices

  • Offer WebAuthn as primary (best UX + security)
  • TOTP as fallback
  • Avoid SMS MFA (SS7 attacks, SIM swap)
  • Require MFA for all admin/privileged actions
  • Step-up auth for sensitive operations (payments)
  • Remember trusted devices (cookie + device fingerprint)


為什麼要學MFA 與無密碼認證?

MFA 與無密碼認證 是 security-iam 課程的核心章節之一。

在真實世界中

MFA 與無密碼認證 並不是課本上的理論——它在真實的軟體開發中頻繁出現。無論你是正在接案、準備面試,還是想要提升自己的技術深度,理解這個主題都能讓你直接受益。

你將從本章獲得

  • 🎯 完整的知識體系:從核心原理到實作細節,條理分明
  • 💻 可運行的程式碼:每段程式碼都是完整的,可直接執行
  • 🔍 除錯技巧:常見錯誤的分析與解決方案
  • 🚀 下一步指引:學完後該往哪個方向繼續深入

銜接下一章

本章為你建立了 MFA 與無密碼認證 的完整知識基礎。下一章將在此基礎上,帶你探索更進階的真實世界應用場景——你將學會如何將本章所學應用到更複雜的問題中。

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!