Last active
October 21, 2024 13:43
-
-
Save aescalana/7e0bc39b95baa334074707f73bc64bfe to your computer and use it in GitHub Desktop.
Decode and Encode Flask's session cookie. Great for testing purposes; only the secret key is needed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from flask.sessions import SecureCookieSessionInterface | |
from itsdangerous import URLSafeTimedSerializer | |
class SimpleSecureCookieSessionInterface(SecureCookieSessionInterface): | |
# Override method | |
# Take secret_key instead of an instance of a Flask app | |
def get_signing_serializer(self, secret_key): | |
if not secret_key: | |
return None | |
signer_kwargs = dict( | |
key_derivation=self.key_derivation, | |
digest_method=self.digest_method | |
) | |
return URLSafeTimedSerializer(secret_key, salt=self.salt, | |
serializer=self.serializer, | |
signer_kwargs=signer_kwargs) | |
def decodeFlaskCookie(secret_key, cookieValue): | |
sscsi = SimpleSecureCookieSessionInterface() | |
signingSerializer = sscsi.get_signing_serializer(secret_key) | |
return signingSerializer.loads(cookieValue) | |
# Keep in mind that flask uses unicode strings for the | |
# dictionary keys | |
def encodeFlaskCookie(secret_key, cookieDict): | |
sscsi = SimpleSecureCookieSessionInterface() | |
signingSerializer = sscsi.get_signing_serializer(secret_key) | |
return signingSerializer.dumps(cookieDict) | |
if __name__=='__main__': | |
sk = 'youWillNeverGuess' | |
sessionDict = {u'Hello':'World'} | |
cookie = encodeFlaskCookie(sk, sessionDict) | |
decodedDict = decodeFlaskCookie(sk, cookie) | |
assert sessionDict==decodedDict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment