You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将django-two-factor-auth与Django REST Framework结合实现?

django-two-factor-auth与Rest API的集成方案

可以把django-two-factor-auth和Rest API结合使用,不用换库,通过自定义视图就能适配API场景,核心模型也不需要完全重写,具体方案如下:

  • 自定义API视图对接核心逻辑
    这个库的双因素认证核心逻辑(令牌验证、设备管理)并没有和模板强绑定,你可以跳过它自带的模板视图,自己基于Django REST Framework写API视图,直接调用库的核心方法:

    • 验证TOTP令牌时,调用two_factor.views.utils.validate_token方法校验用户提交的令牌
    • 注册双因素设备时,直接操作two_factor.models.TOTPDevice模型创建用户关联的设备实例
      示例代码:
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework import status
    from two_factor.views.utils import validate_token
    from two_factor.models import TOTPDevice
    
    class TOTPVerifyAPIView(APIView):
        def post(self, request):
            # 假设用户已通过基础认证(比如JWT)
            user = request.user
            token = request.data.get('token')
            try:
                device = TOTPDevice.objects.get(user=user, confirmed=True)
                if validate_token(device, token):
                    return Response({'status': 'success', 'message': '双因素验证通过'})
                return Response({'status': 'fail', 'message': '无效令牌'}, status=status.HTTP_400_BAD_REQUEST)
            except TOTPDevice.DoesNotExist:
                return Response({'status': 'fail', 'message': '未绑定双因素设备'}, status=status.HTTP_404_NOT_FOUND)
    
  • 复用现有模型,按需扩展
    库自带的TOTPDevice、PhoneDevice等模型已经覆盖了TOTP、短信验证码等主流双因素场景,直接复用即可。如果需要扩展设备信息(比如添加设备名称、备注),可以通过模型继承或者一对一关联的方式扩展,不需要重新定义核心模型。

  • 备选库参考
    如果觉得适配django-two-factor-auth的成本太高,也可以选择专门为REST API设计的双因素认证库:

    • django-rest-framework-two-factor:基于DRF封装,直接提供现成的API视图和序列化器,开箱即用
    • django-otp:django-two-factor-auth的底层依赖,更轻量化,适合完全自定义REST风格的双因素流程

内容的提问来源于stack exchange,提问作者fullstacknoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:15:50