**pyjwt使用教程: **
https://pyjwt.readthedocs.io/en/stable/
使用案例
import datetime
from flask import Flask, request
# 导入pyjwt
import jwt
app = Flask(__name__)
app.secret_key = "456sdcjhkgahsiugfijbxcad6745#@#@!%^&&."
@app.route('/login')
def login():
# 设置载荷信息
payload = {
"userid": 888,
# 过期时间要用0时区的。
"exp": datetime.datetime.utcnow()+datetime.timedelta(days=1)
}
# 加密并获取token
token = jwt.encode(payload, key=app.secret_key)
return "token: %s" % token
@app.route('/usercenter')
def usercenter():
# 直接通过请求头拿(会携带类型,比如: Bearer + TOKEN)
# 此时就需要split切分后才能进行jwt的decode校验
print(request.headers.get("Authorization"))
# 我们可以通过request的authorization属性直接拿到token,里面帮我们按token和type两个属性切分了
print(request.authorization.token) # 具体的token
print(request.authorization.type) # Bearer 或者 JWT
# 解码必须直接提供token,不能带有Bearer类型字符串
#(这样不能解码的!) Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjg4OCwiZXhwIjoxNjg0MTMyNjgxfQ.KWWBcSEBxF2uo7ZYWIX69ZuGyeBi-eiV8doRt1bh0z4
#(只能这样!) eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjg4OCwiZXhwIjoxNjg0MTMyNjgxfQ.KWWBcSEBxF2uo7ZYWIX69ZuGyeBi-eiV8doRt1bh0z4
# 解码后得到playload,注意:解码的时候必须告诉他用什么算法
try:
jwt_decode = jwt.decode(request.authorization.token, key=app.secret_key, algorithms=["HS256"])
print(jwt_decode.get("userid"))
return jwt_decode
except Exception as e:
print(e)
return "token校验出错!"
if __name__ == '__main__':
app.run(debug=True)
标签:__,flask,request,app,jwt,token,使用,pyjwt
From: https://www.cnblogs.com/juelian/p/17742120.html