How to decode a Flask session or a CSRF token

I’m using this example. The only change I made is return_timestamp=True parameter to find when the session was generated.

import hashlib
from itsdangerous import URLSafeTimedSerializer
from flask.sessions import TaggedJSONSerializer

def decode_session_cookie(secret_key, cookie_str):
    salt = 'cookie-session'
    serializer = TaggedJSONSerializer()
    signer_kwargs = {
        'key_derivation': 'hmac',
        'digest_method': hashlib.sha1
    }
    s = URLSafeTimedSerializer(secret_key, salt=salt, 
        serializer=serializer, signer_kwargs=signer_kwargs)
    return s.loads(cookie_str, return_timestamp=True)

The same way it can be done for the csrf_token.

def decode_csrf_token(secret_key, csrf_token):    
    salt = 'wtf-csrf-token'
    s = URLSafeTimedSerializer(secret_key, salt=salt)
    return s.loads(csrf_token, return_timestamp=True)
comments powered by Disqus