My previous article introduced a Node.js module, node-jsjws, for performant generation and verification of JSON Web Signatures and JSON Web Tokens.

Brian J Brennan's python-jws is a nice module for generating and verifying JSON Web Signatures in Python. I've already written some unit tests for node-jsjws which show that the JSON Web Signatures it generates can be verified by python-jws and vice versa.

Note that I had to make some minor changes to python-jws in order to add support for the RSASSA-PSS signature algorithms (PS256, PS384 and PS512).

Interoperability between node-jsjws and python-jws is useful because it means a Web site written in Python can send a JSON Web Signature to another site running on Node.js, for example.

I wanted to be able to do the same with JSON Web Tokens: send a token from a site running on Google App Engine, for example, to a service running on Node.js.

Introducing python-jwt

python-jws does have a JWT example, minijwt, but as its name suggests it's a limited implementation of JSON Web Tokens.

I've added the following things to the JWT header and turned minijwt into a standalone module, python-jwt:

  • Expiry date and time of the token (exp).
  • Date and time at which the token was generated (iat).
  • Date and time from which the token is generated (nbf).
  • A unique identifier for the token (jti).

exp, iat and nbf are checked against the current time when a token is verified.

I also added support for the none signature algorithm (i.e. an empty signature).


Here's a simple example using a key generated by PyCrypto:

import jwt, Crypto.PublicKey.RSA as RSA, datetime
key = RSA.generate(2048)
payload = { 'foo': 'bar', 'wup': 90 };
token = jwt.generate_jwt(payload, key, 'PS256', datetime.timedelta(minutes=5))
header, claims = jwt.verify_jwt(token, key)
for k in payload: assert claims[k] == payload[k]

The expiry time of the token is set to 5 minutes.

The API documentation is linked to from the python-jwt homepage. python-jwt comes with a full set of unit tests (including interoperability with node-jsjws) and some benchmarks.

I've decided not to compare benchmark results with node-jsjws because I don't want to get into comparing Node.js with Python.

blog comments powered by Disqus