Python JWT library PyJWT trouble signing with HS256 - HMAC using SHA-256 hash algorithm

Viewed 6606

Trying to generate a JWT token using the PyJWT library.

When I use the below program to generate the JWT token - the token does not work.

However when I use the website https://jwt.io/ with the same details - the token works. Is there something that I'm missing.

I need python generate the token properly so I can automate some API's that need this token.

Python program:

import jwt
import base64

code = jwt.encode({'sub':'String','nbf':'1501594247',
                   'exp':'1501767047', 'iss': 'string', 'aud': 'String'},
       base64.b64encode('secret'), algorithm='HS256')
print code

Example:

code = jwt.encode({'sub':'AccountNUmber.QTVR','nbf':'1501594247','exp':'1501860089', 'iss': 'client_id', 'aud': 'https://login.google.com/oauth'},
                  base64.b64encode('secret'), algorithm='HS256')

Result:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjbGllbnRfaWQiLCJhdWQiOiJodHRwczovL2xvZ2luLmdvb2dsZS5jb20vb2F1dGgiLCJzdWIiOiJBY2NvdW50TlVtYmVyLlFUVlIiLCJleHAiOiIxNTAxODYwMDg5IiwibmJmIjoiMTUwMTU5NDI0NyJ9.dRUUQYJ-RmxgoExwPyrvHPzX9SsxcpX1rOWlhisxNsg

Token generated by https://jwt.io/ :

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjbGllbnRfaWQiLCJhdWQiOiJodHRwczovL2xvZ2luLmdvb2dsZS5jb20vb2F1dGgiLCJzdWIiOiJBY2NvdW50TlVtYmVyLlFUVlIiLCJleHAiOiIxNTAxODYwMDg5IiwibmJmIjoiMTUwMTU5NDI0NyJ9.INp-ZnnL8Uj7MIwLYmpZtGyTyZG-oqZRNW8iZ145jVs

The token generated by https://jwt.io/ works when I call the endpoint. And I get a status code 200 (Success).

However when I use the token generated from my program it gives 'Invalid Token' - 400 (Bad Request).

2 Answers

there is an error in documentation, I checked the source code of this library

class PyJWT(PyJWS):
    header_type = 'JWT'

    @staticmethod
    def _get_default_options():
        # type: () -> Dict[str, bool]
        return {
            'verify_signature': True,
            'verify_exp': True,
            'verify_nbf': True,
            'verify_iat': True,
            'verify_aud': True,
            'verify_iss': True,
            'require_exp': False,
            'require_iat': False,
            'require_nbf': False
        }

    def encode(self,
               payload,  # type: Union[Dict, bytes]
               key,  # type: str
               algorithm='HS256',  # type: str
               headers=None,  # type: Optional[Dict]
               json_encoder=None  # type: Optional[Callable]
               ):
        # Check that we get a mapping
        if not isinstance(payload, Mapping):
            raise TypeError('Expecting a mapping object, as JWT only supports '
                            'JSON objects as payloads.')

        # Payload
        for time_claim in ['exp', 'iat', 'nbf']:
            # Convert datetime to a intDate value in known time-format claims
            if isinstance(payload.get(time_claim), datetime):
                payload[time_claim] = timegm(payload[time_claim].utctimetuple())  # type: ignore

        json_payload = json.dumps(
            payload,
            separators=(',', ':'),
            cls=json_encoder
        ).encode('utf-8')

        return super(PyJWT, self).encode(
            json_payload, key, algorithm, headers, json_encoder
        )

So the solution be will

from jwt.api_jwt import PyJWT


payload = {
    'id': 5,
    'email': 'ASDASDA'
}

key = 'secret'

jwt_Obj=PyJWT()
jwt_token = jwt_Obj.encode( payload=payload,key= key )
decode_token=jwt_Obj.decode(jwt_token,key=key)

print (jwt_token)
print(decode_token)

Output should or (must) be b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6IkFTREFTREEiLCJpZCI6NX0.-Woz4Crgi5KZj_D99eGaKxY4VxosY7r_e7HTD9JaDqE'

{'email': 'ASDASDA', 'id': 5}

Related