17
π How to Handle with JWTs in Python
JSON Web Tokens, or JWTs for short, are all over the web. They can be used to track bits of information about a user in a very compact way and can be used in APIs for authorization purposes. This post will cover what JSON Web Tokens are and how to create JWTs in Python using the most popular JWT library: PyJWT. We are also going to see how you can sign and verify JWTs in Python using asymmetric algorithms.
Before we get started, there's a collection of scripts with all the code I'm going to cover in this blog post available in this GitHub repository.
JSON Web Tokens are a very compact way to carry information. They are defined as a 3 part structure consisting of a header, a payload, and a signature.
The header and payload both have what we call claims, they are statements about an entity and all additional data that needs to be passed in the request:
- In the header, we find claims about the token itself, like what algorithm was used for signing that token;
- While the payload (or the body) carries information about a given asset. In a login scenario, this would be information about the user.
The final part is the signature, and it helps you ensure that a given token wasn't tampered with because signing JWTs requires either a secret or a public/private key pair agreed on previously. The signature itself is based on the header and payload, in combination with a secret, or private/public key pair, depending on the algorithm.
Claims follow the standard key-value pairing that you see in dictionaries and JSON objects, and most of the claims commonly used in JWTs have a standardized naming defined in the JWT specification (RFC7519). In the RFC7519, you'll also find the description of what each claim means.
If you want to know more about JWTs, you should check this page that talks about JSON web tokens in a very practical way, or if you want a more in-depth resource, I recommend the "JWT Handbook" available for free in the link below.
While it's nice to read definitions and explanations, it's sometimes more beneficial to actually see how something works. In the rest of this article, you'll learn the ins and outs of JSON Web Tokens by creating, signing, verifying, and decoding your very own JWT.
17