How do I sign and verify JSON Web Tokens (JWT) in Python?

In Python, you can sign and verify JSON Web Tokens (JWT) using the `PyJWT` library. Below is an example of how to create a JWT, sign it, and then verify it.

import jwt import datetime # Secret key for signing the JWT secret_key = "your_secret_key" # Create a payload with an expiration time payload = { 'user_id': 123, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=30) # Token valid for 30 seconds } # Sign the JWT token = jwt.encode(payload, secret_key, algorithm='HS256') print("Generated JWT:", token) # Verify the JWT try: decoded_payload = jwt.decode(token, secret_key, algorithms=['HS256']) print("Decoded JWT Payload:", decoded_payload) except jwt.ExpiredSignatureError: print("Token has expired") except jwt.InvalidTokenError: print("Invalid Token")

Python JWT JSON Web Tokens PyJWT Token Signing Token Verification