科普
Json Web Token JWT三部分组成:
(1)Header
(2)Payload
(3)Signature
Header.Payload.Signature
Base64URL 算法:
Base64 有三个字符+、/和=,在 URL 里面有特殊含义,
所以要被替换掉:=被省略、+替换成-,/替换成_
代码实现
github:https://github.com/jpadilla/pyjwt/
文档:https://pyjwt.readthedocs.io/en/latest/index.html
安装
pip install PyJWT
复制jwt网站的数据进行加解密测试
代码示例
# -*- coding: utf-8 -*-
import jwt
data = {
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
# 加密 py3加密后是字节型数据
encoded = jwt.encode(data, 'secret', algorithm='HS256')
print(encoded.decode())
# eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
# eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
# DzMJlzRbt6kdh1Kbbqv8SA8QsddwfSoM1bqw41tQY2k
print(jwt.decode(encoded, 'secret', algorithms=['HS256']))
# {'sub': '1234567890', 'name': 'John Doe', 'iat': 1516239022}
增加过期时间,Python3代码示例
# -- coding: utf-8 --
import time
from datetime import datetime, timedelta
import jwt
class JwtUtil(object):
def __init__(self, key):
self.key = key
def encode(self, payload, expires=7):
"""
获取token
:param payload: dict
:param expires: 过期时间:天
:return: str
"""
# 使用utc时间
payload['exp'] = datetime.utcnow() + timedelta(days=expires)
return jwt.encode(payload=payload, key=self.key).decode()
def decode(self, token):
"""
验证并解析token
:param token: str
:return: dict
"""
return jwt.decode(jwt=token, key=self.key)
</div>