Encode Decode JWT

JWT stands for JSON Web Tokens.

A simple function to encode the content -

'''
Encode the given text with given secret key. The default number of seconds for token validity is 600 seconds.
'''
def encode_token(text, secret_key, validity_seconds = 600):
    import datetime, jwt
    try:
        payload = {
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=validity_seconds),
            'iat': datetime.datetime.utcnow(),
            'secret': text
        }
        return jwt.encode(
            payload,
            secret_key,
            algorithm='HS256'
        )
    except Exception as e:
        return e

And to decode -

'''
Decode the encoded token with given secret_key
'''
def decode_token(auth_token, secret_key):
    import jwt
    try:
        payload = jwt.decode(auth_token, secret_key, algorithms='HS256')
        return {'auth': True, 'error': '', 'decoded': payload}
    except jwt.ExpiredSignatureError:
        return {'auth': False, 'error': 'Token expired'}
    except jwt.InvalidTokenError:
        return {'auth': False, 'error': 'Invalid token'}
    return {'auth': False, 'error': 'Some error'}

Let's get to work -

Define a secret

secret = 'This-is-my-super-secret'

Encode the content

encoded_data = encode_token('Something to encode', secret)
print(encoded_data)

This outputs as -

'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjcyMjY4NDUsImlhdCI6MTYyNzIyNjI0NSwic2VjcmV0IjoiU29tZXRoaW5nIHRvIGVuY29kZSJ9.CombVr-757PXau8yeXtyjCLn54E3pGNntlnpoADnPRI'

If You copy this to https://jwt.io you will see -

Decode the token

To decode the data you need the same secret

decoded_data = decode_token(encoded_data, secret)
print(decoded_data['decoded']['secret'])

This outputs to -
'Something to encode'

If you try to decode using some other secret key, the data won't be decoded correctly

decoded_data = decode_token(encoded_data, 'some-other-secret')
print(decoded_data)

This output as -

{'auth': False, 'error': 'Invalid token'}

Hope these simple functions help you :)

You can follow me on Twitter — @kravigupta . You can also connect on LinkedIn — kravigupta.

25