我有一个简单的登录系统,我用烧瓶做了。 登录后,我向用户返回一种令牌,用户可以使用该令牌在另一个路由上发送聊天等消息。
我想在一段时间后(例如一分钟(使该令牌过期,令牌将过期,用户必须再次登录才能获得新令牌。
所以我的问题是,到期后如何删除令牌或类似的东西?
用户登录后,我将登录时间保存在这样的字典中:
login_time[datetime.datetime.now()] = data['username']
然后我想在聊天路线之前或聊天路线中做这样的事情:
for time, user in login_time.items():
if datetime.datetime.now() >= time + datetime.timedelta(seconds=30):
del login_time[time]
但我不知道我应该把它放在哪里以及它将如何工作。
这是聊天路由的一部分:
@app.route('/chat', methods=['POST'])
def chat():
try:
data = request.get_json()
username = verify_token(data['token']) # Verifying if token is in tokens list
validate_message(data['message']) # Verifying if message is not empty
chats.append(username + ": " + data['message'])
for i, u in login_time.items(): # Not sure about this part
if i != u:
abort(400, 'Your token is expired, please login again')
return jsonify(chats)
如果您不想使用 JWT,一个易于实现的解决方案是:
- 生成令牌时,同时生成到期日期
- 在数据库中记录两者
- 当用户尝试发布消息时,其令牌将与消息一起发送
- 检查令牌是否仍然有效(检查 datetime.now(( 是否> token_expiration_time或者您甚至可以让脚本每隔 x 分钟从数据库中删除每个过期的令牌,然后检查令牌是否在数据库中找到(
- 如果令牌已过期,则重定向用户并要求他再次登录以生成另一个令牌。
使用基于令牌的身份验证时,您必须识别并验证该令牌的访问,即识别客户端(这是哪个用户(并验证检查令牌有效性,如过期
您可以将此数据合并到令牌本身中(JWT
(
let's say the token is smth like 'token-1571153241', where the number is unix timestamp of expiration
1) parse the expiration timestamp from the token
2) if expiration reached return expiry message, else serve the request
* keep in mind to issue the token with the expiry date
或
使用任何数据库存储令牌的信息
1) parse the token from the request
2) check the db for the token validity
3) pass or reject based the criteria
方法1在性能方面更好,不需要访问外部源(DB(,但对令牌属性的控制较少,例如很难手动实现令牌的手动过期(或更改用户权限访问(