TL;DR
This guide shows you how to make sure a client is allowed to use a JSON Web Token (JWT) before letting them access your system. We’ll cover checking the token’s signature, expiry time, and any extra claims you need.
Checking JWT Authorization
- Understand the JWT Structure
- A JWT has three parts: Header, Payload, and Signature.
- The Header contains information about the signing algorithm (e.g., HS256).
- The Payload holds the claims – data about the user or client. This is where you’ll find things like user ID, roles, and permissions.
- The Signature verifies that the token hasn’t been tampered with. It’s created using a secret key.
This is the most important step! You need to use the same secret key used to sign the token.
- Many libraries exist for different programming languages (e.g.,
python-josein Python,jsonwebtokenin Node.js). - Here’s an example using a hypothetical library:
token = "your_jwt_token"secret_key = "your_super_secret_key"try: decoded_payload = verify_jwt(token, secret_key) except InvalidSignatureError: print("Token signature is invalid") # Reject the token except ExpiredSignatureError: print("Token has expired") # Reject the token except Exception as e: print(f"An error occurred: {e}") #Reject the token - The
verify_jwtfunction is a placeholder; replace it with your library’s equivalent.
JWTs have an expiry time to limit their validity. Always check this!
- The
expclaim in the payload specifies the expiration timestamp (in seconds since epoch). - After verification, access the
expclaim from the decoded payload.import time current_time = int(time.time()) if decoded_payload['exp'] < current_time: print("Token has expired") # Reject the token
You might add extra claims to control access (e.g., role, permissions).
- After successful signature and expiry checks, examine these custom claims.
if decoded_payload['role'] != 'admin': print("User does not have admin privileges") # Reject the token or limit access
Sometimes you need to revoke tokens before their expiry time (e.g., user logs out).
- Maintain a list of revoked JWTs (e.g., in a database or cache).
- Before accepting a token, check if it’s on the revocation list.
Your secret key is critical! Never hardcode it directly into your code.
- Use environment variables or a secure secrets management system.