JSON Web Tokens implemented
I have now successfully implemented JSON Web Tokens on this blog
I could not find any simple and easy to use resources for it, so I created it myself.
I have not yet figured out how to make a login system, but I have heard a lot of interesting things about JSON Web Tokens.
def jwt_sign(data):
if not isinstance(data, bytes):
if not isinstance(data, str): data = json.dumps(data)
data = data.encode()
header = base64.urlsafe_b64encode(json.dumps({'typ': 'JWT', 'alg': 'HS256'}).encode()).strip(b'=')
body = base64.urlsafe_b64encode(data).strip(b'=')
signature = base64.urlsafe_b64encode(hmac.digest(secret, header + b'.' + body, hashlib.sha256)).strip(b'=')
return f'{header.decode()}.{body.decode()}.{signature.decode()}'
def jwt_validate(token: str):
try:
header, _, signature = map(lambda s: base64.urlsafe_b64decode(s + '=='), token.split('.'))
header = json.loads(header)
assert header['typ'] == 'JWT'
assert header['alg'] == 'HS256'
string_to_compare = '.'.join(token.split('.')[:2]).encode()
digest = hmac.digest(secret, string_to_compare, digest=hashlib.sha256)
matches = hmac.compare_digest(digest, signature)
return matches
except:
return False
I'm actually quite proud of it! You can then take a token, like this one:
eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9.eyJ1c2VybmFtZSI6ICJhZG1pbiJ9.do4Q8dUylbpDQ4hpD9RrjQWv-HetNeC1et2XFfoc4fc
And put it as a "token" cookie. Of course, I have added some code to make sure that this specific JWT is not able to be used.
Written by: admin