Skip to content

Instantly share code, notes, and snippets.

@sujeetkv
Last active June 17, 2019 09:04
Show Gist options
  • Save sujeetkv/c76c23b3caee9e35d8f1fd9b9256a4f6 to your computer and use it in GitHub Desktop.
Save sujeetkv/c76c23b3caee9e35d8f1fd9b9256a4f6 to your computer and use it in GitHub Desktop.
JSON Web token in python
from itsdangerous import (
TimedJSONWebSignatureSerializer as TokenSerializer,
BadSignature, SignatureExpired
)
class AuthToken(object):
"""AuthToken class"""
SECRET_KEY = 'secret-key'
@classmethod
def generate(cls, payload, expires_in=3600, salt=b'auth-token-salt'):
"""Generate token
Returns a token string
:param payload: data to attach with token
:param expires_in: validity of token in seconds
:param salt: salt string for token
"""
s = TokenSerializer(cls.SECRET_KEY, expires_in=expires_in)
return s.dumps(payload, salt=salt)
@classmethod
def verify(cls, token, salt=b'auth-token-salt'):
"""Verify token
Returns a tuple containing verify result and payload
:param token: token string to verify
:param salt: salt string for token
"""
s = TokenSerializer(cls.SECRET_KEY)
try:
payload = s.loads(token, salt=salt)
except SignatureExpired as e:
# expired token
return False, e.payload
except BadSignature:
# invalid token
return None, None
# valid token
return True, payload
@classmethod
def set_secret_key(cls, secret_key):
"""Set secret key
Returns AuthToken class
:param secret_key: secret key string
"""
cls.SECRET_KEY = secret_key
return cls
from auth_token import AuthToken
validity = 3600 # 1 hour
token = AuthToken.generate({'user_id': 45}, validity)
token_valid, token_data = AuthToken.verify(token)
if token_valid is None:
# token invalid
elif token_valid is False:
# token expired
# token_data['user_id'] == 45
else:
# token valid
# token_data['user_id'] == 45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment