July 2017
Beginner to intermediate
340 pages
7h 43m
English
In Python, the PyJWT (https://pyjwt.readthedocs.io/) library provides all the tools you need to generate and read back JWT tokens.
Once you've pip-installed pyjwt (and cryptography), you can use the encode() function and the decode() functions to create tokens.
In the following example, we're creating a JWT token using HMAC-SHA256 and reading it back. The signature is verified when the token is read, by providing the secret:
>>> import jwt >>> def create_token(alg='HS256', secret='secret', **data): ... return jwt.encode(data, secret, algorithm=alg) ... >>> def read_token(token, secret='secret', algs=['HS256']): ... return jwt.decode(token, secret) ... >>> token = create_token(some='data', inthe='token') >>> print(token) b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpbnRoZSI6InRva2VuIiwic29tZSI6ImRhdGEifQ.oKmFaNV-C2wHb_WaMAfIGDqBPnOCyOzVf-JWvh-6bRQ' ...