Skip to content

Instantly share code, notes, and snippets.

@anachronic
Created March 5, 2019 03:44
Show Gist options
  • Save anachronic/442a291b0194ba310627501363d5e8df to your computer and use it in GitHub Desktop.
Save anachronic/442a291b0194ba310627501363d5e8df to your computer and use it in GitHub Desktop.
JWT creation and verification using python-jose
from jose import jwt
from jose.jwt import JWTClaimsError, JWTError, ExpiredSignatureError
from datetime import datetime, timedelta
import time
key = 'secret#%$sdfasdkflj@#%RFsaior82340-fweASDFSD928354940k'
expdelta = timedelta(seconds=10)
now = datetime.utcnow()
exp = now + expdelta
payload = {
'iss': 'calce',
'nbf': now,
'iat': now,
'exp': exp
}
token = jwt.encode(payload, key, algorithm='HS256')
# this fails because of issuer
try:
claims = jwt.decode(token, key, issuer='pepito')
except JWTClaimsError:
print('failed validation with issuer pepito')
# Now validate and should be ok
try:
claims = jwt.decode(token, key, issuer="calce")
print('token verification succeeded')
except JWTError:
print('token verification failed!')
# wait 11 seconds to make it fail
print('waiting 11 seconds. hold on. btw, signature should fail after this message')
time.sleep(11)
try:
claims = jwt.decode(token, key, issuer="calce")
print('signature still verifies, whaT!')
except ExpiredSignatureError:
print('Signature expired, bummer!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment