google authenticator python_python 实现google authenticator 认证

1.背景

google auth 作为二次认证,大多场景下都使用在ssh 登录下,而且在ssh 的场景下使用,

搭建相对比较简单,本文将介绍google auth 使用在应用平台的二次认证,如:单点登录,

网站登录等平台,增加平台的安全性认证。

#ssh 的搭建可以参考另外一篇博客 https://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.客户扫描图片,前端页面验证用户名和密码后,显示对应的条形码图片

参考另外一篇博客:https://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

你可能感兴趣的:(google,authenticator,python)