我是燒瓶的初學者,我想用 JWT 保護我的應用程式。我使用 pyjwt python 庫。是否可以在pyjwt中重繪 jwt?很多關于 flask-jwt-extended 的資訊,但沒有關于 pyjwt 的資訊。
uj5u.com熱心網友回復:
PyJWT 是一個 Python 庫,它允許您對 JSON Web 令牌進行編碼和解碼
此庫尚未為用戶會話做好準備。您應該自己實作重繪 邏輯:
import jwt
from datetime import datetime, timedelta, timezone
payload = {"username": "john", "session_id": "abc"}
# add token expiration time (5 seconds):
payload["exp"] = datetime.now(tz=timezone.utc) timedelta(seconds=5)
# this token is valid for 5 seconds
token = jwt.encode(payload, "some_secret_phrase", algorithm="HS256")
# get token data:
decoded_payload = jwt.decode(token, "some_secret_phrase", algorithms=["HS256"])
# if we run ↑this↑ after 5 seconds jwt.exceptions.ExpiredSignatureError: Signature has expired will be raised
# in other case we will get decoded data:
# {'username': 'john', 'session_id': 'abc', 'exp': 1650187206}
# now we should update 'exp' for 5 seconds again
decoded_payload['exp'] = datetime.now(tz=timezone.utc) timedelta(seconds=5)
# and generate new token
new_token = jwt.encode(payload, "some_secret_phrase", algorithm="HS256")
# after receiving this new token client will be able to use it for 5 seconds before another refreshing process
我的示例非常簡單、不安全,只是演示了如何重繪 令牌。對于真正的 Web 應用程式,您必須使用更復雜的邏輯和重繪 令牌。
uj5u.com熱心網友回復:
我也是初學者。
客戶端可以決議訪問令牌的過期時間。如果訪問令牌已過期,那么您必須根據您的演算法請求帶有重繪 令牌的新訪問令牌。
這是一個簡單的參考來源。
https://github.com/nevertheless-good/fastapi-jwt-auth-server.git
祝你好運。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/459289.html
