Back
+20 XP
Concept

JWT (JSON Web Tokens) Creation & Verification

A JWT is three Base64URL-encoded strings separated by dots: `header.payload.signature`. The signature is an HMAC-SHA256 of `header.payload` created with a secret key, ensuring tamper-proof stateless authentication 🎟️.

python
import hmac, hashlib, base64, json

def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")

header = b64url(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
payload = b64url(json.dumps({"sub": "user_42", "role": "admin"}).encode())

secret = b"my-ultra-secure-key"
message = f"{header}.{payload}".encode()
sig = b64url(hmac.new(secret, message, hashlib.sha256).digest())

token = f"{header}.{payload}.{sig}"
print(f"Stateless JWT: {token[:45]}... 🎟️")

# 42. JWT (JSON Web Tokens) Creation & Verification A JWT is three Base64URL-encoded strings separated by dots: `header.payload.signature`. The signature is an HMAC-SHA256 of `header.payload` created with a secret key, ensuring tamper-proof stateless authentication 🎟️. ```python import hmac, hashlib, base64, json def b64url(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") header = b64url(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()) payload = b64url(json.dumps({"sub": "user_42", "role": "admin"}).encode()) secret = b"my-ultra-secure-key" message = f"{header}.{payload}".encode() sig = b64url(hmac.new(secret, message, hashlib.sha256).digest()) token = f"{header}.{payload}.{sig}" print(f"Stateless JWT: {token[:45]}... 🎟️") ``` Because the server verifies JWTs using its secret HMAC key, it doesn't need to query a session database on every API request — making microservices completely stateless! 🎟️ --- ### Question What happens if a user alters the `role` in the JWT payload from 'user' to 'admin' in their browser? 🧠 - [ ] a. The server's recomputed signature will not match the token's signature, instantly rejecting the token as tampered 🎟️ - [ ] b. The server automatically accepts the change - [ ] c. The token is decrypted into plain text - [ ] d. The browser is permanently blocked --- ### Challenge Construct a JWT token from header `{"alg": "HS256"}` and payload `{"uid": 1}` using HMAC-SHA256 and secret `b"sec"`. Print whether `len(token.split(".")) == 3`. 🎯 <details> <summary>Solution</summary> ```python import hmac, hashlib, base64, json def b64(d): return base64.urlsafe_b64encode(d).rstrip(b"=").decode() h = b64(json.dumps({"alg": "HS256"}).encode()) p = b64(json.dumps({"uid": 1}).encode()) msg = f"{h}.{p}".encode() s = b64(hmac.new(b"sec", msg, hashlib.sha256).digest()) jwt = f"{h}.{p}.{s}" print(len(jwt.split(".")) == 3) ``` </details>

Checkpoint

What happens if a user alters the `role` in the JWT payload from 'user' to 'admin' in their browser? 🧠

Practice

Construct a JWT token from header `{"alg": "HS256"}` and payload `{"uid": 1}` using HMAC-SHA256 and secret `b"sec"`. Print whether `len(token.split(".")) == 3`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks