如果我为我的API创建一个令牌:
def generate_auth_token(self, **kwargs):
s = Serializer(app.config['SECRET_KEY'], expires_in = 172800)
return s.dumps({ 'id': kwargs['user_id'] })
如何结束用户的会话?
答案 0 :(得分:2)
如果这是令牌中的唯一信息,则无法进行。您可以通过向令牌有效负载添加更多信息来解决此问题,并可能存储有关有效令牌服务器端的额外信息。
例如,您可以存储电子邮件和密码的哈希值,因此如果更改,哈希将不再进行比较
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
这是通过哈希完成的,而不是直接包含电子邮件和密码,因为令牌是签名但不是加密。
如果您希望能够在不更改电子邮件或密码的情况下使所有令牌无效,则可以为每个用户存储一些随机密钥并将其添加到散列中。生成新的随机密钥将使所有先前的令牌无效。
您还可以更进一步,只需存储完整的令牌服务器端,在注销时删除它们,以便它们不能再次使用。