【问题标题】:Adding a second or multiple device for a user django two factor authentication为用户添加第二个或多个设备 django 双因素身份验证
【发布时间】:2023-04-01 07:10:01
【问题描述】:

我在 Django 项目中使用two-factor authentication。它工作正常,但我想在我的代码中实现更多功能。但我无法实施

预期行为:

我希望用户在从新设备登录时必须面对 2F 身份验证提示。另外,我想增加代码验证时间。

当前行为: 目前,如果用户首次登录,则会向用户显示身份验证提示。但是当用户从新设备登录时,不会向用户显示身份验证并轻松登录。但我希望用户必须面对每个新设备的 2F。此外,每当我更改步骤时,验证代码都无效。例如,如果我给出 step=60,那么验证码就会无效。我无法增加代码验证的时间。

我检查了数据库中的 TOTPDevice 模型。它表明现在没有为新设备生成新密钥。

我正在使用以下代码。

def get_user_totp_device(self, user, confirmed=None):
    """
    Gets user's time based one-time password devices
    """
    devices = devices_for_user(user, confirmed=confirmed)
    for device in devices:
        if isinstance(device, TOTPDevice):
            return device

class TOTPCreateView(APIView):
permission_classes = []

def post(self, request):
    username = request.data['username']
    user = User.objects.get(username=username)
    user_email = user.email
    user_device = request.META.get('HTTP_USER_AGENT', '')
    time = datetime.now().strftime("%H:%M:%S")
    if not user.is_anonymous:
        device = get_user_totp_device(self, user)
        if not device:
            device = user.totpdevice_set.create(confirmed=False)
            secret_key = device.bin_key
            totp = pyotp.TOTP(base64.b32encode(secret_key))
            one_time_password = totp.now()
        url = device.config_url

        response_status = status.HTTP_201_CREATED
    else:
        url = {}
        response_status = status.HTTP_401_UNAUTHORIZED

    return Response(url, status=response_status)

class TOTPVerifyView(APIView):
permission_classes = []

def post(self, request, token, format=None):
    username = request.data['username']
    user = User.objects.get(username=username)
    device = get_user_totp_device(self, user)

    if not user.is_anonymous:
        device_registered = device.verify_token(token)
        if device_registered:
            if not device.confirmed:
                device.confirmed = True
                device.save()
            data = True
            response_status = status.HTTP_200_OK
        else:
            data = {'error': 'Verification code is not valid'}
            response_status = status.HTTP_400_BAD_REQUEST
    else:
        data = False
        response_status = status.HTTP_401_UNAUTHORIZED

    return Response(data, status=response_status)

【问题讨论】:

    标签: django two-factor-authentication


    【解决方案1】:

    我能想到的最简单的方法是创建一个新表并在该表中针对该用户存储machine_id 之类的内容。然后你可以创建一个permission_classdecorator 来检查用户是在一台新机器上还是在与DB 相同machine_id 的旧机器上。在这种情况下,您将转到视图的其余部分并返回任何内容。另一方面,如果用户在新机器上,您可以将他们重定向到 2FA 页面,然后将该新机器添加到您的数据库中针对该用户。

    我能想到的另一种方法是在前端填充,但不推荐你可以让你的前端从本地存储向你发送一些验证凭据,如果这些凭据不存在,你知道用户要么在新设备或在很长一段时间后访问或其他。在这种情况下,您将它们重定向到 2FA 页面。

    我希望我解释得很好。

    【讨论】:

      猜你喜欢
      • 2015-10-05
      • 2021-06-26
      • 2019-07-21
      • 2022-11-08
      • 2016-05-22
      • 1970-01-01
      • 2019-07-21
      • 2015-12-10
      • 2012-09-11
      相关资源
      最近更新 更多