如题,在上一文章中分析了3rd_session和OpenId的关系,为确保随机散列值和OpenId的唯一对应关系,完全可以借助Flask中的itsdangerous 的TimedJSONWebSignatureSerializer来实现这一目标,具体操作流程如下:
step1: Flask中导入相应的库:
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
def gen_3rdsession(openId):
# 用OpenId加密生成3rdsession
s = Serializer(current_app.config['SECRET_KEY'])
third_session = s.dumps({'openId': openId})
return third_session
def gen_openId(thirdsession):
# 用3rdsession解密生成OpenId
s = Serializer(current_app.config['SECRET_KEY'])
openId = s.loads(thirdsession)['openId']
return openId
step2:生成3rdsession:
third_session = gen_3rdsession(openId)
这个3rdsession本身就是Bsion格式,类似于Json,可以直接返回。
step3:然后在小程序中获取:
var third_session = data.data;
console.log(third_session)
try {wx.setStorageSync('third_session', third_session)}
catch (e) {}
将其保存在本地缓存中。
step4:接下来就是在POST数据时,将third_session提交至服务器进行解密获取Openid,进而在数据库查询用户的相关数据。
呵呵,该加密应该是绝对安全的,每次加密的数据是不一样的,加密后的OpenId==3rd_session如下:
eyJhbGciOiJIUzI1NiIsImV4cCI6MTQ5MzI2NDc5NCwiaWF0IjoxNDkzMjYxMTk0fQ.eyJvcGVuSWQiOiJvaXJiczBMT1dyajF2ZDRzVHAtamNxd1FWNy1JIn0.GM2THjHKYM_Rt8gBJuZcWNwDxxz1TgoAZCKLyOWs9Uk