Reputation: 3034
Using flask, I'm attempting to verify a cookie has not been tampered with. Right now, if I change the cookie value, it just throws up an error but I'm wanting to check with code is_valid(session['user_id']) and redirect/reset if not.
someone in #pocoo says:
- actually, you could call SecureCookie.unserialize and catch the exception
- ah, it fails silently
- looks like you have to try unserializing it and check if you get an empty object from it
Could anyone explain further what this code would look like?
Upvotes: 1
Views: 1478
Reputation: 35731
Look at https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/contrib/securecookie.py#L265
safe_str_cmp(client_hash, mac.digest())
is performing the check that should fail if the cookie has been tampered with.
Depending on what you exactly would like to catch, you could jump in in different places. You could do
data = request.cookies.get("session")
cookie = werkzeug.contrib.securecookie.SecureCookie.unserialize(data, secret_key)
If there is data
and cookie
does not contain any data, the unserialization failed. One of many reasons is that safe_str_cmp()
(being called in unserialize()
) returned False.
Upvotes: 1