栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 实现google authenticator 认证

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 实现google authenticator 认证

  • 1.背景
    google auth 作为二次认证,大多场景下都使用在ssh 登录下,而且在ssh 的场景下使用,
    搭建相对比较简单,本文将介绍google auth 使用在应用平台的二次认证,如:单点登录,
    网站登录等平台,增加平台的安全性认证。
    #ssh 的搭建可以参考另外一篇博客  http://blog.51cto.com/12113362/2050514

  • 2.实现原理
    1.使用pyotp 的python模块生成google auth 需要的密钥
    2.根据密钥生成条形码图片
    3.使用google authenticator 客户端扫描条形码,客户端根据时间及密钥经过算法
    生成6位数的验证码
    4.平台二次认证通过对输入的验证码进行校验,校验也是基于时间和密钥

  • 3.代码实现

    • a.密钥生成
      import pyotp
      gtoken = pyotp.random_base32() #获取随机密钥,存于用户表中

  • b.生成条形码图片,根据用户名及密钥生成条形码图片
    from qrcode import QRCode,constants
    def get_qrcode(secret_key,username):
    base_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
    filepath = base_DIR + '/app/static/img/qrcode/'
    data = pyotp.totp.TOTP(secret_key).provisioning_uri(username, issuer_name="Verfiy Code")
    qr = QRCode(
    version=1,
    error_correction=constants.ERROR_CORRECT_L,
    box_size=6,
    border=4,)
    try:
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image()
    img.save(filepath+secret_key+'.png') #保存条形码图片
    return True
    except Exception,e:
    return False

  • c.客户扫描图片,前端页面验证用户名和密码后,显示对应的条形码图片
    参考另外一篇博客:http://blog.51cto.com/12113362/2050335

  • d.校验验证码的正确性
    import  pyotp
    def Google_Verify_Result(secret_key,verifycode):
    t = pyotp.TOTP(secret_key)
    result = t.verify(verifycode) #对输入验证码进行校验,正确返回True
    msg = result if result is True else False
    return msg

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/222127.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号