python3生成token和验证

本文详细介绍了使用Python实现用户密码的加密存储与验证,以及基于JWT的用户认证令牌的生成与验证过程。通过具体代码示例,展示了如何利用passlib库进行密码哈希处理,以及itsdangerous库生成和验证令牌。
# -*- coding: utf-8 -*-

from passlib.apps import custom_app_context as pwd_context
import config
import MySQLdb,datetime
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired

class QXPasswd(object):
    def __init__(self, password):
        self.password = password
    def generate_password(self):
        password_hash = pwd_context.encrypt(self.password)
        return password_hash

    def verify_password(self, password_hash):
        return pwd_context.verify(self.password, password_hash)

class QXToken(object):
    def __init__(self, name):
        self.name = name

    def generate_auth_token(self, expiration = 3600):
        s = Serializer(config.SECRET_KEY, expires_in = expiration)
        return s.dumps({'name': self.name })

    def verify_auth_token(self, token):
        s = Serializer(config.SECRET_KEY)
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None # valid token, but expired
        except BadSignature:
            return None # invalid token
        return data['name'] == self.name
         



#插入一条用户密码加密的数据
'''
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db='qixin', port=3306, charset="utf8")
cursor = conn.cursor()
now = datetime.datetime.now()
currentTime = now.strftime("%Y-%m-%d %H:%M:%S")
sql = "insert into qx_user(username,password,addTime) values(%s, %s, %s)"
u = QXPasswd('123456')

value = ['zl', u.generate_password(), currentTime]
cursor.execute(sql, value)
conn.commit()
'''

#验证用户密码正确性
'''
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db='qixin', port=3306, charset="utf8")
cursor = conn.cursor()
sql="select username, password from qx_user where username = 'zl'"
cursor.execute(sql)
row = cursor.fetchone()
u = QXPasswd('123456')
print u.verify_password(row[1])
'''

#生成用户token
'''
token = QXToken('zl')
print token.generate_auth_token()
'''

#验证token
token = QXToken('zl')
print token.verify_auth_token('eyJhbGciOiJIUzI1NiIsImV4cCI6MTQ2NDI1NzI4OCwiaWF0IjoxNDY0MjUzNjg4fQ.eyJuYW1lIjoiemwifQ.iVlCfzIk5YMXhlzO3lOqHBBtYTiJV3_ze8wUR80GWAc')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值