2015-04-02 35 views
2

如果我創建一個令牌,我的API是這樣的:註銷或結束會話使用itsdangerous簽署

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

我如何可以結束用戶的會話?

+0

我的回答有用嗎?你還在找別的東西嗎? – davidism 2015-04-13 16:14:09

回答

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 

這在哈希完成,而不是僅僅包括電子郵件地址和密碼直接因爲令牌是,簽署的是而不是加密

如果您希望能夠在不更改電子郵件或密碼的情況下使所有令牌失效,則可以爲每個用戶存儲一些隨機密鑰並將其添加到散列中。生成一個新的隨機密鑰將使以前的所有令牌失效。

你也可以更進一步,只需存儲完整的令牌服務器端,在註銷時刪除它們,以便它們不能再次使用。