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
        payload = {
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=validity_seconds),
            'iat': datetime.datetime.utcnow(),
            'secret': text
        return jwt.encode(
    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
        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)

This outputs as -


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)

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')

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.