jpadilla / pyjwt

JSON Web Token implementation in Python
https://pyjwt.readthedocs.io
MIT License
5.18k stars 690 forks source link

Add parameter for user-supplied timestamp when validating claims #921

Closed lesinigo closed 11 months ago

lesinigo commented 1 year ago

PyJWT currently hardcodes calls to datetime.now() and uses the result to validate timestamp-related claims (such as iat, nbf and exp).

This prevents to validate the claims against a user-provided timestamp, preventing deterministic unit testing of code that calls into PyJWT and possibly some more exotic use cases. My unit tests are now dependent on the current system time and I need to mock it to make them deterministic and repeatable.

I propose to introduce a new parameter to the .decode() method or possibly in its options dict, current_time: typing.Optional[datetime.datetime], defaults to None. When it is None the current logic applies (and this makes it 100% backwards compatible), when it is not None PyJWT will use the provided datetime instead of calling into datetime.now().

I made my example on PyJWT.decode() but this should obviously extended to all public-facing methods that end reading the current system time from datetime or time or anything else.

github-actions[bot] commented 11 months ago

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days