Table of contents
It's been the pain of my career to explain JWTs and read articles that just spit jargon and make it confusing to understand what the hell this thing is. So, let's break it down simply.
What is JWT?
JWT stands for JSON Web Tokens. But a better name would be "signed JSON string". That's really all it is!
What is signing?
Signing a string in computer science means we do some fancy math stuff that guarantees the original wasn't tampered with. But let's break it down further:
Signing is like putting a wax seal on a letter. It doesn't hide the content (that's what encryption does), but it ensures that the letter hasn't been altered since the sender sealed it. If someone tries to change the content, the seal would break, and you'd know it's been tampered with.
This is different from encryption, which hides the content from the public, and hashing, which creates a unique fingerprint of the data but doesn't allow you to recover the original content.
Signing lets you verify the authenticity while still being able to read the content.
You can skip this
How signing works
Creating a signature: When you sign data, you use a secret key (known only to you) and a signing algorithm. This algorithm takes your data and the secret key as inputs and produces a unique string of characters called a signature.
Attaching the signature: The signature is then attached to the original data. In the case of JWT, the signature is added as part of the token.
Verifying the signature: When someone receives the signed data, they can use the same algorithm and the public key (in symmetric systems like JWT, the same secret is used) to recreate the signature. If the recreated signature matches the one attached to the data, it proves that the data hasn't been tampered with and was signed by someone who knows the secret key.
Tamper-evident: If even a single character in the original data is changed, the signature verification will fail. This is because the signature is intrinsically tied to the exact content of the data.
JWT In action
Here's a simple Python example of how JWT works:
pythonCopyimport jwt
secret = 'secure_password'
payload = {"userId": 1, "email": 'example@email.com'}
# Create a JWT
token = jwt.encode(payload, secret, algorithm="HS256")
# Verify and decode the JWT
try:
decoded = jwt.decode(token, secret, algorithms=["HS256"])
print("Decoded JWT:", decoded)
except jwt.InvalidTokenError:
print("Invalid token!")
# If we get here, woohoo! We're sure this data is valid and we can read the message
In this example, we're using the pyjwt
library to handle JWT operations. We create a JWT by encoding our payload (the JSON data) with a secret key. Then we can decode it later using the same secret key. If the token has been tampered with or the wrong secret is used, it will raise an error.
And that's it! JWT is just a way to pass around JSON data that we can trust hasn't been tampered with. Simple, right?