如何使用django-two-factor-auth为django中的现有用户获取OTP令牌

问题描述

我正在为django编写硒测试。我想使用硒通过UI通过OTP登录用户登录后,进入设置页面,我应该在其中输入由Google Authenticator生成的6位数字令牌。 django-two-factor-auth将每个用户的密钥存储在表otp_totp_totpdevice中。我假设Google Authenticator应该使用此密钥来生成令牌。

以下是我到目前为止尝试过的操作:它生成错误的令牌。

import hmac,base64,struct,hashlib,time


def get_hotp_token(secret,intervals_no):
    key=base64.b64decode(secret,validate=True)
    msg = struct.pack(">Q",intervals_no)
    h = hmac.new(key,msg,hashlib.sha1).digest()
    o = h[19] & 15
    h = (struct.unpack(">I",h[o:o + 4])[0] & 0x7fffffff) % 1000000
    return h


def get_totp_token(secret):
    return get_hotp_token(secret,intervals_no=int(time.time()) // 30)

解决方法

如果我们有一个device = user.totpdevice_set.create(name='default') 尚未创建OTP,请创建一个:

user

如果我们的from django_otp.oath import totp device = user.totpdevice_set.get() token = totp(device.bin_key) print(token) 已经创建了OTP,则忽略上述步骤。 要获取令牌,请执行以下操作:

cow <- as.vector(unique(df$Gender),mode="list") #returns a list with two items,"Male" and "Female"
cow_2 <- sapply(cow,fp_text,font.size=8,italic=F,bold=F,underlined=F,color='black',simplify=F)
,

PyOTP library

解决了这个问题

一旦你有了设备......

import pyotp


uri = device.config_url
parsed_uri = pyotp.parse_uri(uri)
secret = parsed_uri.secret
otp_token = pyotp.TOTP(secret).now()