How to Validate a JWT Signature in Python with a Mock Secret
Validates a JWT's signature using a mock secret, decoding and handling expired or invalid tokens gracefully.
pip install PyJWT
Python code
24 linesimport jwt
import time
SECRET = "mock_secret_key_123"
def validate_token(token):
try:
payload = jwt.decode(token, SECRET, algorithms=["HS256"])
return f"Valid token. Payload: {payload}"
except jwt.ExpiredSignatureError:
return "Token expired"
except jwt.InvalidTokenError:
return "Invalid token"
if __name__ == "__main__":
# Create a valid token
valid_token = jwt.encode({"user": "alice", "exp": time.time() + 3600}, SECRET, algorithm="HS256")
# Create a token with wrong secret
wrong_secret_token = jwt.encode({"user": "bob", "exp": time.time() + 3600}, "wrong_secret", algorithm="HS256")
print("Valid token:", validate_token(valid_token))
print("Wrong secret token:", validate_token(wrong_secret_token))
print("Tampered token:", validate_token("not.a.jwt"))
Output
Valid token: Valid token. Payload: {'user': 'alice', 'exp': 1717123456.789012}
Wrong secret token: Invalid token
Tampered token: Invalid token
How it works
The jwt.decode function verifies the token's signature using the provided secret and algorithm (HS256). It returns the payload as a dictionary if the signature is valid and the token is not expired. If the token is expired, an ExpiredSignatureError is raised. For any other invalid token (bad signature, malformed data), InvalidTokenError is caught. This pattern ensures robust handling of token validation in production code.
Common mistakes
- Using a hardcoded secret in production code instead of environment variables.
- Not checking the algorithm parameter, which can allow algorithm confusion attacks.
- Forgetting to catch `jwt.ExpiredSignatureError` separately from other invalid token errors.
Variations
- Use `jwt.decode` with `options={'verify_exp': False}` to ignore expiration when needed.
- Load the secret from an environment variable using `os.getenv('JWT_SECRET')`.
Real-world use cases
- Verifying JWT tokens in an API gateway before allowing access to protected endpoints.
- Validating authentication tokens in a microservice to ensure requests come from trusted clients.
- Testing internal services with mock tokens that use a known secret in development environments.
Sponsored
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.