-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_jwt.py
More file actions
117 lines (96 loc) · 3.24 KB
/
generate_jwt.py
File metadata and controls
117 lines (96 loc) · 3.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python3
"""
JWT Token Generator for Rusta-rs Gateway
This script generates valid JWT tokens that match your current gateway configuration.
"""
import jwt
import json
from datetime import datetime, timedelta, timezone
# Configuration from your config.json
SECRET = "your-super-secure-jwt-secret-key-must-be-at-least-32-characters-long"
ISSUER = "Rusta-gateway"
AUDIENCE = "api-clients"
REQUIRED_CLAIMS = ["sub", "exp"]
def generate_token(user_id="testuser123", expires_in_hours=24):
"""
Generate a JWT token with the correct configuration.
Args:
user_id (str): Subject identifier for the token
expires_in_hours (int): Token expiration time in hours
Returns:
str: Valid JWT token
"""
# Current time
now = datetime.now(timezone.utc)
# Create payload with required claims
payload = {
"sub": user_id, # Subject (required)
"exp": now + timedelta(hours=expires_in_hours), # Expiration (required)
"iat": now, # Issued at
"iss": ISSUER, # Issuer
"aud": AUDIENCE, # Audience
"user_id": user_id, # Custom claim
"role": "user" # Custom claim
}
# Generate token
token = jwt.encode(payload, SECRET, algorithm="HS256")
return token
def verify_token(token):
"""
Verify a JWT token with the current configuration.
Args:
token (str): JWT token to verify
Returns:
dict: Decoded payload if valid, None if invalid
"""
try:
payload = jwt.decode(
token,
SECRET,
algorithms=["HS256"],
issuer=ISSUER,
audience=AUDIENCE,
options={"require": ["sub", "exp"]}
)
return payload
except jwt.InvalidTokenError as e:
print(f"Token validation error: {e}")
return None
def main():
print("🔑 Rusta-rs JWT Token Generator")
print("=" * 50)
# Generate new token
print("\n1. Generating new JWT token...")
token = generate_token(user_id="testuser123", expires_in_hours=24)
print(f"✅ Token generated successfully!")
# Display token
print(f"\n📋 Your JWT Token (valid for 24 hours):")
print("-" * 50)
print(token)
print("-" * 50)
# Verify the token works
print(f"\n🔍 Verifying token...")
payload = verify_token(token)
if payload:
print("✅ Token is valid!")
print(f"📄 Payload: {json.dumps(payload, indent=2, default=str)}")
else:
print("❌ Token verification failed!")
# Generate curl command
print(f"\n🚀 curl command to test:")
print("-" * 50)
curl_cmd = f"""curl --location 'http://localhost:5900/protected/cats/404' \\
--header 'Authorization: Bearer {token}'"""
print(curl_cmd)
print("-" * 50)
# Generate Postman format
print(f"\n📮 For Postman:")
print(f"Authorization Header: Bearer {token}")
print(f"\n✨ Token expires: {datetime.now(timezone.utc) + timedelta(hours=24)}")
if __name__ == "__main__":
try:
main()
except ImportError:
print("❌ PyJWT library not found!")
print("📦 Install it with: pip install PyJWT")
print("🔧 Or run: python3 -m pip install PyJWT")