Create bearer_token.py
Browse files- bearer_token.py +35 -0
bearer_token.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import base64
|
| 3 |
+
import hashlib
|
| 4 |
+
import hmac
|
| 5 |
+
import os
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
|
| 8 |
+
class BearerTokenGenerator:
|
| 9 |
+
@staticmethod
|
| 10 |
+
def get_bearer(body: str, path: str = "/chats/stream") -> tuple:
|
| 11 |
+
# 从环境变量获取 SECRET_AUTH_PREFIX 和 SECRET_KEY
|
| 12 |
+
secret_auth_prefix_str = os.environ.get('SECRET_AUTH_PREFIX')
|
| 13 |
+
secret_key_str = os.environ.get('SECRET_KEY')
|
| 14 |
+
|
| 15 |
+
if not secret_auth_prefix_str or not secret_key_str:
|
| 16 |
+
raise ValueError("SECRET_AUTH_PREFIX or SECRET_KEY environment variables are not set")
|
| 17 |
+
|
| 18 |
+
# 将字符串转换为字节列表
|
| 19 |
+
secret_auth_prefix = bytes(ast.literal_eval(secret_auth_prefix_str))
|
| 20 |
+
secret_key = bytes(ast.literal_eval(secret_key_str))
|
| 21 |
+
|
| 22 |
+
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 23 |
+
prefix = f"POST:{path}:{timestamp}\n".encode()
|
| 24 |
+
to_sign = prefix + body.encode()
|
| 25 |
+
|
| 26 |
+
signature = BearerTokenGenerator.generate_signature(to_sign, secret_key)
|
| 27 |
+
auth_prefix_base64 = base64.b64encode(secret_auth_prefix).decode()
|
| 28 |
+
|
| 29 |
+
bearer_token = f"Bearer {auth_prefix_base64}.{signature}"
|
| 30 |
+
return bearer_token, timestamp
|
| 31 |
+
|
| 32 |
+
@staticmethod
|
| 33 |
+
def generate_signature(to_sign: bytes, secret_key: bytes) -> str:
|
| 34 |
+
h = hmac.new(secret_key, to_sign, hashlib.sha256)
|
| 35 |
+
return base64.b64encode(h.digest()).decode()
|