python3微信公众号开发:产生token及token验证的方法

2018-12-2615:59:22后端程序开发Comments3,864 views字数 1587阅读模式

做微信公众号开发在进行网页授权时,微信需要用户自己在授权url中带上一个类似token的state的参数,以防止跨站攻击。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

在经过再三思考之后,自己试着实现一个产生token和验证token的方案。接下就把code贴出来。希望读者指导一下。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

2、产生token文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

原理:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

通过hmac sha1 算法产生用户给定的key和token的最大过期时间戳的一个消息摘要,将这个消息摘要和最大过期时间戳通过":"拼接起来,再进行base64编码,生成最终的token文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

实现:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

import time
import base64
import hmac

def generate_token(key, expire=3600):
 r'''
 @Args:
  key: str (用户给定的key,需要用户保存以便之后验证token,每次产生token时的key 都可以是同一个key)
  expire: int(最大有效时间,单位为s)
 @Return:
  state: str
 '''
 ts_str = str(time.time() + expire)
 ts_byte = ts_str.encode("utf-8")
 sha1_tshexstr = hmac.new(key.encode("utf-8"),ts_byte,'sha1').hexdigest() 
 token = ts_str+':'+sha1_tshexstr
 b64_token = base64.urlsafe_b64encode(token.encode("utf-8"))
 return b64_token.decode("utf-8")

3、验证token文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

原理:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

将token进行base64解码,通过token得到token最大过期时间戳和消息摘要。判断token是否过期。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

如没过期才将 从token中的取得最大过期时间戳进行hmac sha1 算法运算(注意这里的key要与产生token的key要相同),最后将产生的摘要与通过token取得消息摘要进行对比, 如果两个摘要相等,则token有效,否则token无效 。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

实现:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

import time
import base64
import hmac

def certify_token(key, token):
 r'''
 @Args:
  key: str
  token: str
 @Returns:
  boolean
 '''
 token_str = base64.urlsafe_b64decode(state).decode('utf-8')
 token_list = token_str.split(':')
 if len(token_list) != 2:
 return False
 ts_str = token_list[0]
 if float(ts_str) < time.time():
 # token expired
 return False
 known_sha1_tsstr = token_list[1]
 sha1 = hmac.new(key.encode("utf-8"),ts_str.encode('utf-8'),'sha1')
 calc_sha1_tsstr = sha1.hexdigest()
 if calc_sha1_tsstr != known_sha1_tsstr:
 # token certification failed
 return False 
 # token certification success
 return True 

4、用法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

key = "JD98Dskw=23njQndW9D"
# 一小时后过期
token = generate_token(key, 3600)

certify_token(key, token)

5、Note!!!文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

本代码只能在python3.x 中运行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

以上这篇python 产生token及token验证的方法就是菜鸟小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持菜鸟学院(www.cainiaoxueyuan.com)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9087.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/9087.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定