适配更多移动端。
针对浏览器同源机制,支持跨站传输
json-web-token
token = header.payload.signature
header:声明编码格式
payload:保存业务数据和有效期(格林威治时间)
signature:签名。把header跟payload,以及secret-key进行加密,默认HS256(sha256)算法
python中的哈希模块:hashlib 哈希的作用之一:用来去重
?
import jwt
from flask import current_app
def generate_jwt(payload, expiry, secret=None):
"""
生成jwt
:param payload: dict 载荷
:param expiry: datetime 有效期
:param secret: 密钥
:return: jwt
"""
_payload = {'exp': expiry}
_payload.update(payload)
if not secret:
secret = current_app.config['JWT_SECRET']
token = jwt.encode(_payload, secret, algorithm='HS256')
return token.decode()
def verify_jwt(token, secret=None):
"""
检验jwt
:param token: jwt
:param secret: 密钥
:return: dict: payload
"""
if not secret:
secret = current_app.config['JWT_SECRET']
try:
payload = jwt.decode(token, secret, algorithm=['HS256'])
except jwt.PyJWTError:
payload = None
return payload
|