Flask 注销或使用其签名结束会话

Flask 注销或使用其签名结束会话,flask,token,access-token,Flask,Token,Access Token,如果我为我的API创建一个令牌,如下所示: def generate_auth_token(self, **kwargs): s = Serializer(app.config['SECRET_KEY'], expires_in = 172800) return s.dumps({ 'id': kwargs['user_id'] }) 如何结束用户会话?如果这是令牌中唯一的信息,则无法结束。您可以通过向令牌负载添加更多信息,并可能存储关于服务器端有效令牌的额外信息来解决此问题

如果我为我的API创建一个令牌,如下所示:

def generate_auth_token(self, **kwargs):
    s = Serializer(app.config['SECRET_KEY'], expires_in = 172800)
    return s.dumps({ 'id': kwargs['user_id'] })

如何结束用户会话?

如果这是令牌中唯一的信息,则无法结束。您可以通过向令牌负载添加更多信息,并可能存储关于服务器端有效令牌的额外信息来解决此问题

例如,您可以存储电子邮件和密码的散列,因此,如果其中任何一个发生更改,该散列将不再进行比较

from hashlib import md5
from werkzeug.security import safe_str_cmp

# generate the hash and store it in the token along with the id
hash = md5('{}{}'.format(user.email, user.password).encode('utf8')).hexdigest()

###

# load the user from the id in the token and generate its hash
hash = md5('{}{}'.format(user.email, user.password).encode('utf8')).hexdigest()

# then compare the hash in the token to the hash for the user
if not safe_str_cmp(hash, token['hash']):
    # don't log in user
这是在散列中完成的,而不仅仅是直接包含电子邮件和密码,因为令牌已签名但未加密

如果您希望能够在不更改电子邮件或密码的情况下使所有令牌无效,您可以为每个用户存储一些随机密钥,并将其添加到哈希中。生成新的随机密钥将使以前的所有令牌无效

您还可以更进一步,只需在服务器端存储完整的令牌,在注销时将其删除,这样就不能再次使用