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.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 12 views 0 copies

Requires third-party packages — install first
pip install PyJWT

Python code

24 lines
Python 3.9+
import 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

stdout
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

  1. Use `jwt.decode` with `options={'verify_exp': False}` to ignore expiration when needed.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from API design & gRPC

Related tutorials and quizzes for this topic.