generate_token.py
2.04 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
"""
Generate JWT token for API testing
"""
import datetime
import yaml
from dotenv import load_dotenv
import os
# 尝试导入不同的 JWT 库
try:
import jwt
# 检查是否有 encode/decode 方法
if not hasattr(jwt, 'encode') or not hasattr(jwt, 'decode'):
# 如果没有,尝试 python-jose
from jose import jwt
except ImportError:
# 如果都失败了,尝试 python-jose
from jose import jwt
def generate_test_token():
"""Generate a test JWT token"""
# Load config
load_dotenv()
with open('config.yml', 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
def replace_env_vars(obj):
if isinstance(obj, dict):
return {k: replace_env_vars(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [replace_env_vars(item) for item in obj]
elif isinstance(obj, str) and obj.startswith('${') and obj.endswith('}'):
env_var = obj[2:-1]
default = None
if ':' in env_var:
env_var, default = env_var.split(':', 1)
return os.getenv(env_var, default)
return obj
config = replace_env_vars(config)
# Get JWT settings
secret = config['jwt']['secret']
algorithm = config['jwt']['algorithm']
subject = config['jwt']['subject']
expires_hours = config['jwt']['expires_hours']
# Create payload
payload = {
'sub': subject,
'iat': datetime.datetime.utcnow(),
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=expires_hours),
'service_id': 'test-service'
}
# Generate token
token = jwt.encode(payload, secret, algorithm)
print("Generated JWT Token:")
print("=" * 50)
print(token)
print("=" * 50)
print(f"Subject: {subject}")
print(f"Algorithm: {algorithm}")
print(f"Expires in: {expires_hours} hours")
print()
print("Use this token in Authorization header:")
print(f"Authorization: Bearer {token}")
return token
if __name__ == "__main__":
generate_test_token()