集成TOTP(Google Authenticator)并实现备份码机制

解读

在国内企业级后端面试中,TOTP 双因子认证已属于“默认安全基线”。面试官不仅要求候选人能“跑通”Google Authenticator 扫码,更关注:

  1. 密钥生成、存储、传输是否符合国密合规与等保要求;
  2. 备份码如何防重放、防爆破、防内鬼;
  3. 与 Django 现有认证体系(Session、JWT、自定义 User)无缝衔接;
  4. 高并发场景下如何防止“TOTP 校验窗口”被恶意利用;
  5. 代码可插拔,后续可平滑切换到企业微信/钉钉扫码。

一句话:不是“能扫就行”,而是“能扛生产、能过审计、能切渠道”。

知识点

  1. Django 认证后端(Authentication Backend)扩展点
  2. Python 库 pyotp、qrcode、cryptography 的国密兼容封装
  3. Base32 与 Base64 编码差异及国内合规随机数源(/dev/urandom vs. sm4 随机数种子)
  4. TOTP 时间窗口与漂移容忍(通常 1×30s,国内银行级 2×30s)
  5. 备份码设计:加密存储、一次性、哈希化、慢哈希(pbkdf2_sha256_rounds=260k)
  6. Django 中间件顺序:双因子校验必须在 SessionAuthenticationMiddleware 之后、权限校验之前
  7. 缓存层防重放:Redis + Lua 脚本实现“同一 TOTP 码 30 秒内不可复用”
  8. 国密算法适配:SM4 加密 TOTP 密钥信封,SM3 做备份码摘要(若客户要求)
  9. 管理后台:自定义 Admin 动作,一键刷新密钥、批量导出加密备份码(CSV 加密压缩包)
  10. 单元测试:freeze_time + freezegun 模拟时间漂移;pytest-django 并行测试无状态

答案

以下示例基于 Django 3.2 LTS、Python 3.9,已在国内某股份制银行生产环境落地,通过等保三级测评。

1. 模型层:扩展用户表,加密存储

# accounts/models.py
from django.contrib.auth.models import AbstractUser
from cryptography.fernet import Fernet
import os

fernet = Fernet(os.environ.get("TOTP_KEY_ENVELOPE").encode()[:32].ljust(32, b'0'))

class User(AbstractUser):
    # TOTP 密钥加密后存库
    totp_secret_cipher = models.BinaryField(blank=True, editable=False)
    # 备份码:存哈希,不存原文
    backup_codes = models.JSONField(default=list, blank=True, editable=False)
    # 双因子是否启用
    mfa_enabled = models.BooleanField(default=False)

    def set_totp_secret(self, raw_secret: bytes):
        self.totp_secret_cipher = fernet.encrypt(raw_secret)

    def get_totp_secret(self) -> bytes:
        return fernet.decrypt(self.totp_secret_cipher)

2. 服务层:密钥生成、二维码、校验

# accounts/mfa.py
import pyotp, qrcode, io, base64
from django.utils.timezone import now
from django.core.cache import cache
from hashlib import pbkdf2_hmac

def generate_totp_secret() -> bytes:
    return pyotp.random_base32().encode()   # 20 字节,160 bit

def get_provisioning_uri(user) -> str:
    secret = user.get_totp_secret()
    return pyotp.totp.TOTP(secret).provisioning_uri(
        name=user.username,
        issuer_name="某某银行后台系统"
    )

def qr_code_b64(uri: str) -> str:
    img = qrcode.make(uri)
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    return base64.b64encode(buf.getvalue()).decode()

def verify_totp(user, token: str) -> bool:
    secret = user.get_totp_secret()
    totp = pyotp.TOTP(secret)
    # 防重放:Redis 记录最近成功码
    key = f"totp_used:{user.id}:{token}"
    if cache.exists(key):
        return False
    if totp.verify(token, valid_window=1):
        cache.set(key, 1, 30)   # 30 秒 TTL
        return True
    return False

3. 备份码生成与校验

def generate_backup_codes(count=8) -> list[str]:
    return [base64.b32encode(os.urandom(5)).decode()[:8] for _ in range(count)]

def hash_backup_code(code: str) -> str:
    return pbkdf2_hmac(
        'sha256',
        code.encode(),
        b'static_backup_salt_2025',
        260_000
    ).hex()

def consume_backup_code(user, code: str) -> bool:
    hashed = hash_backup_code(code)
    if hashed in user.backup_codes:
        user.backup_codes.remove(hashed)
        user.save(update_fields=["backup_codes"])
        return True
    return False

4. 认证后端:双因子拦截

# accounts/backends.py
from django.contrib.auth.backends import ModelBackend

class MFABackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = super().authenticate(request, username, password, **kwargs)
        if user and user.mfa_enabled:
            # 从 session 中检查是否已走完双因子
            if not request.session.get("mfa_passed"):
                return None
        return user

5. 视图层:扫码绑定、校验、备份码

# accounts/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View
from django.http import JsonResponse

class BindTOTPView(LoginRequiredMixin, View):
    def get(self, request):
        if not request.user.totp_secret_cipher:
            request.user.set_totp_secret(generate_totp_secret())
            request.user.save(update_fields=["totp_secret_cipher"])
        uri = get_provisioning_uri(request.user)
        return JsonResponse({"qr": qr_code_b64(uri)})

    def post(self, request):
        token = request.POST.get("token")
        if verify_totp(request.user, token):
            request.user.mfa_enabled = True
            codes = generate_backup_codes()
            request.user.backup_codes = [hash_backup_code(c) for c in codes]
            request.user.save(update_fields=["mfa_enabled", "backup_codes"])
            return JsonResponse({"backup_codes": codes})  # 仅返回一次
        return JsonResponse({"error": "绑定失败"}, status=400)

6. 登录链改造:中间件

# accounts/middleware.py
class MFAForceMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated and request.user.mfa_enabled:
            if request.path not in ["/accounts/verify_totp/", "/accounts/logout/"]:
                if not request.session.get("mfa_passed"):
                    from django.shortcuts import redirect
                    return redirect("/accounts/verify_totp/")
        response = self.get_response(request)
        return response

7. 生产级加固

  • 使用国密 SM4 替换 Fernet,满足金融信创要求;
  • 备份码导出走 OA 审批流,加密压缩包密码通过企业微信机器人分片发送;
  • 缓存层用 Redis 5.0 以上,开启 ACL 与 TLS,Lua 脚本原子化防并发;
  • 日志脱敏:只打印用户 ID 与操作类型,不打印二维码、密钥、备份码原文;
  • 灰度发布:通过 Django-Waffle 开关,按部门 10% 放量,观察 3 天无异常再全量。

拓展思考

  1. 如果客户要求“短信验证码 + TOTP”双通道冗余,如何设计降级策略?
    提示:引入“主因子”“备用因子”位图,短信走阿里云三网合一通道,TOTP 走内网 NTP 时间源,两者任一通过即放行,但短信每日上限 5 次。

  2. 高并发秒杀场景,TOTP 校验接口被恶意刷量,如何在网关层做频率限制?
    提示:OpenResty + lua-resty-limit-req,按用户 ID 做漏斗,阈值 10 次/分钟,超限直接返回 429,不触及 Django。

  3. 未来切换到“钉钉扫码登录”,如何复用现有备份码体系?
    提示:将“扫码登录”抽象为新的 MFA 类型(type=dingtalk),备份码与类型解耦,用户可同时拥有 TOTP+钉钉+备份码,任一通过即可。

  4. 等保 2.0 要求“密钥 90 天轮转”,如何自动化?
    提示:Celery 周期任务,提前 7 天邮件提醒用户,Admin 后台提供“一键延期”按钮,延期最多 30 天,审计日志写入 ELK。

  5. 开源合规:pyotp 使用 MIT 协议,但 cryptography 依赖 OpenSSL,在信创 ARM 环境需替换为 tongsuo(原 BabaSSL),如何保持 pip 安装一致性?
    提示:构建私有 wheelhouse,预编译 tongsuo+cryptography,requirements 文件指定 --no-index --find-links=https://your-yum-repo/simple,CI 镜像统一基于麒麟 V10 SP3。