[英]Using a pyJWT expiration time
我正在做一個小項目。 我有一個老師的裝飾師。 使用我在登錄頁面上生成的 JWT,它可以輸入不同的根。 我想生成具有過期時間的 JWT。 但是有一個問題我可以在Postman中看到過期時間,但是過了那個時間之后我可以使用它。這是我的裝飾器
def teachers():
def wrapper(f):
@wraps(f)
def decorator(*args, **kwargs):
token = request.headers["Authorization"]
token = str.replace(str(token), 'Bearer ', '')
try:
data = jwt.decode(token, "testing",algorithms=["HS256"])
print("Token is still valid and active")
except jwt.ExpiredSignatureError:
print("Token expired. Get new one")
except jwt.InvalidTokenError:
print("Invalid Token")
if data['role'] == "teacher" or data['email'] == "admin@admin.com" :
return f(*args, **kwargs)
else:
return jsonify({"message": "Authentication failed"})
return decorator
return wrapper
和登錄頁面:
@app.route('/teacherlogin', methods=['POST'])
def teacherlogin():
email = request.form["email"]
password = request.form["password"]
role = request.form["role"]
dt=datetime.now()+timedelta(seconds=120)
try:
user = users.find({"$and": [{"email": email}, {"role": role}]})[0]
except IndexError:
return jsonify({"User not found"})
hashed_pw = user["password"]
if bcrypt.hashpw(password.encode('utf8'), hashed_pw) == hashed_pw:
token = jwt.encode({
'email': email,
'password': password,
'role': role,
'exp':dt
}, app.config['SECRET_KEY'])
res = make_response("Successful", 200)
res.set_cookie(
"JWT",
value=token,
expires=dt,
httponly=True)
return res
else:
return jsonify({"error": "Wrong password"})
I can see the expiration time in the Postman cookies section, but I can use it even after this time has passed Postman Cookies: JWT=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSIsInBhc3N3b3JkIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE2NjQyMDkyNTh9.HfanKS-2J50YteuhQg5x_gKQAOd1RPY0DDB64pyCxjU; Path=/; HttpOnly; Expires=Mon, 26 Sep 2022 16:20:58 GMT;
JWT=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSIsInBhc3N3b3JkIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE2NjQyMDkyNTh9.HfanKS-2J50YteuhQg5x_gKQAOd1RPY0DDB64pyCxjU; Path=/; HttpOnly; Expires=Mon, 26 Sep 2022 16:20:58 GMT;
看起來問題是您正在使用datetime.now來生成時間戳。 這將返回本地時間,但 PyJWT 需要 UTC 時間戳。 您可以使用datetime.utcnow獲取 UTC 時間戳。
順便說一句,您不應該在 JWT 中包含敏感信息,例如密碼。 它們只是簽名的; 它們沒有加密。 這意味着任何可以看到 JWT 的人都可以讀取敏感信息。
例如,我使用了您在以下命令中發布的示例 JWT 的第二部分:
echo -n "eyJlbWFpbCI6ImFkbWluQGFkbWluLmNvbSIsInBhc3N3b3JkIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE2NjQyMDkyNTh9" | base64 -d
這給出了以下 output:
{"email":"admin@admin.com","password":"admin","role":"admin","exp":1664209258}
這意味着任何可以讀取 cookie 的人都可以看到密碼,該 cookie 將出現在用戶的瀏覽器中,可能在服務器日志中,如果用戶不使用 HTTPS,則可能在網絡上可見。 (使用Secure cookie 屬性可以防止最后一種情況。)另一個漏洞也總是有可能使攻擊者能夠讀取 cookie。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.