mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-27 04:49:47 +01:00
白名单设备也要校验凭证
白名单以前只认设备自报的地址,认到就直接放行,凭证都不看。现在改成 照样校验凭证,白名单只决定凭证有效期长短。另外做了三件配套:凭证 校验支持传入有效期,不传就沿用原来的默认时长;改配置时把认证属性 一并刷新,之前改了不重启等于没改;连接日志里把 authorization 抹掉, URL 查询串里的凭证也直接忽略,防止凭证落到访问日志里。
This commit is contained in:
parent
eb9dc8ca0f
commit
9d03417fdc
3 changed files with 64 additions and 26 deletions
|
|
@ -19,12 +19,18 @@ class AuthManager:
|
||||||
在 Websocket 中,header:{Device-ID: device_id, Client-ID: client_id, Authorization: Bearer token, ......}
|
在 Websocket 中,header:{Device-ID: device_id, Client-ID: client_id, Authorization: Bearer token, ......}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, secret_key: str, expire_seconds: int = 60 * 60 * 24 * 30):
|
def __init__(
|
||||||
|
self,
|
||||||
|
secret_key: str,
|
||||||
|
expire_seconds: int = 60 * 60 * 24 * 30,
|
||||||
|
issued_after: int = 0,
|
||||||
|
):
|
||||||
if not expire_seconds or expire_seconds < 0:
|
if not expire_seconds or expire_seconds < 0:
|
||||||
self.expire_seconds = 60 * 60 * 24 * 30
|
self.expire_seconds = 60 * 60 * 24 * 30
|
||||||
else:
|
else:
|
||||||
self.expire_seconds = expire_seconds
|
self.expire_seconds = expire_seconds
|
||||||
self.secret_key = secret_key
|
self.secret_key = secret_key
|
||||||
|
self.issued_after = issued_after or 0
|
||||||
|
|
||||||
def _sign(self, content: str) -> str:
|
def _sign(self, content: str) -> str:
|
||||||
"""HMAC-SHA256签名并Base64编码"""
|
"""HMAC-SHA256签名并Base64编码"""
|
||||||
|
|
@ -49,18 +55,28 @@ class AuthManager:
|
||||||
token = f"{signature}.{ts}"
|
token = f"{signature}.{ts}"
|
||||||
return token
|
return token
|
||||||
|
|
||||||
def verify_token(self, token: str, client_id: str, username: str) -> bool:
|
def verify_token(
|
||||||
|
self,
|
||||||
|
token: str,
|
||||||
|
client_id: str,
|
||||||
|
username: str,
|
||||||
|
expire_seconds: int | None = None,
|
||||||
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
验证token有效性
|
验证token有效性
|
||||||
Args:
|
Args:
|
||||||
token: 客户端传入的token
|
token: 客户端传入的token
|
||||||
client_id: 连接使用的client_id
|
client_id: 连接使用的client_id
|
||||||
username: 连接使用的username
|
username: 连接使用的username
|
||||||
|
expire_seconds: 本次校验采用的过期时长,不传时用实例默认值
|
||||||
"""
|
"""
|
||||||
|
expire = self.expire_seconds if expire_seconds is None else expire_seconds
|
||||||
try:
|
try:
|
||||||
sig_part, ts_str = token.split(".")
|
sig_part, ts_str = token.split(".")
|
||||||
ts = int(ts_str)
|
ts = int(ts_str)
|
||||||
if int(time.time()) - ts > self.expire_seconds:
|
if ts < self.issued_after:
|
||||||
|
return False # 签发时刻早于吊销线
|
||||||
|
if int(time.time()) - ts > expire:
|
||||||
return False # 过期
|
return False # 过期
|
||||||
|
|
||||||
expected_sig = self._sign(f"{client_id}|{username}|{ts}")
|
expected_sig = self._sign(f"{client_id}|{username}|{ts}")
|
||||||
|
|
|
||||||
|
|
@ -214,8 +214,12 @@ class ConnectionHandler:
|
||||||
self.client_ip = real_ip.split(",")[0].strip()
|
self.client_ip = real_ip.split(",")[0].strip()
|
||||||
else:
|
else:
|
||||||
self.client_ip = ws.remote_address[0]
|
self.client_ip = ws.remote_address[0]
|
||||||
|
safe_headers = {
|
||||||
|
k: ("***" if k.lower() == "authorization" else v)
|
||||||
|
for k, v in self.headers.items()
|
||||||
|
}
|
||||||
self.logger.bind(tag=TAG).info(
|
self.logger.bind(tag=TAG).info(
|
||||||
f"{self.client_ip} conn - Headers: {self.headers}"
|
f"{self.client_ip} conn - Headers: {safe_headers}"
|
||||||
)
|
)
|
||||||
|
|
||||||
self.device_id = self.headers.get("device-id", None)
|
self.device_id = self.headers.get("device-id", None)
|
||||||
|
|
|
||||||
|
|
@ -60,13 +60,26 @@ class WebSocketServer:
|
||||||
self._intent = modules["intent"] if "intent" in modules else None
|
self._intent = modules["intent"] if "intent" in modules else None
|
||||||
self._memory = modules["memory"] if "memory" in modules else None
|
self._memory = modules["memory"] if "memory" in modules else None
|
||||||
|
|
||||||
auth_config = self.config["server"].get("auth", {})
|
self._load_auth_config(self.config)
|
||||||
|
|
||||||
|
def _load_auth_config(self, config: dict):
|
||||||
|
"""从配置加载认证相关属性,改配置后可重复调用"""
|
||||||
|
auth_config = config["server"].get("auth", {})
|
||||||
self.auth_enable = auth_config.get("enabled", False)
|
self.auth_enable = auth_config.get("enabled", False)
|
||||||
# 设备白名单
|
# 设备白名单:命中白名单只影响 token 签发时长,不再跳过 token 校验
|
||||||
self.allowed_devices = set(auth_config.get("allowed_devices", []))
|
self.allowed_devices = set(auth_config.get("allowed_devices", []))
|
||||||
secret_key = self.config["server"]["auth_key"]
|
# 白名单设备的 token 有效期,默认与普通设备一致,不因白名单放宽
|
||||||
|
self.allowed_expire_seconds = auth_config.get(
|
||||||
|
"allowed_devices_expire_seconds", None
|
||||||
|
)
|
||||||
|
secret_key = config["server"]["auth_key"]
|
||||||
expire_seconds = auth_config.get("expire_seconds", None)
|
expire_seconds = auth_config.get("expire_seconds", None)
|
||||||
self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds)
|
issued_after = auth_config.get("issued_after", 0)
|
||||||
|
self.auth = AuthManager(
|
||||||
|
secret_key=secret_key,
|
||||||
|
expire_seconds=expire_seconds,
|
||||||
|
issued_after=issued_after,
|
||||||
|
)
|
||||||
|
|
||||||
async def start(self):
|
async def start(self):
|
||||||
server_config = self.config["server"]
|
server_config = self.config["server"]
|
||||||
|
|
@ -105,9 +118,10 @@ class WebSocketServer:
|
||||||
if "client-id" in query_params:
|
if "client-id" in query_params:
|
||||||
websocket.request.headers["client-id"] = query_params["client-id"][0]
|
websocket.request.headers["client-id"] = query_params["client-id"][0]
|
||||||
if "authorization" in query_params:
|
if "authorization" in query_params:
|
||||||
websocket.request.headers["authorization"] = query_params[
|
# token 只接受请求头携带,URL 查询串会落进反代访问日志
|
||||||
"authorization"
|
self.logger.bind(tag=TAG).warning(
|
||||||
][0]
|
"忽略 URL 查询串中的 authorization,token 需通过请求头传递"
|
||||||
|
)
|
||||||
|
|
||||||
"""处理新连接,每次创建独立的ConnectionHandler"""
|
"""处理新连接,每次创建独立的ConnectionHandler"""
|
||||||
# 先认证,后建立连接
|
# 先认证,后建立连接
|
||||||
|
|
@ -178,6 +192,8 @@ class WebSocketServer:
|
||||||
)
|
)
|
||||||
# 更新配置
|
# 更新配置
|
||||||
self.config = new_config
|
self.config = new_config
|
||||||
|
# 认证属性跟随配置刷新,避免改配置后不生效
|
||||||
|
self._load_auth_config(new_config)
|
||||||
# 重新初始化组件
|
# 重新初始化组件
|
||||||
modules = initialize_modules(
|
modules = initialize_modules(
|
||||||
self.logger,
|
self.logger,
|
||||||
|
|
@ -213,19 +229,21 @@ class WebSocketServer:
|
||||||
headers = dict(websocket.request.headers)
|
headers = dict(websocket.request.headers)
|
||||||
device_id = headers.get("device-id", None)
|
device_id = headers.get("device-id", None)
|
||||||
client_id = headers.get("client-id", None)
|
client_id = headers.get("client-id", None)
|
||||||
if self.allowed_devices and device_id in self.allowed_devices:
|
token = headers.get("authorization", "")
|
||||||
# 如果属于白名单内的设备,不校验token,直接放行
|
if token.startswith("Bearer "):
|
||||||
return
|
token = token[7:] # 移除'Bearer '前缀
|
||||||
else:
|
else:
|
||||||
# 否则校验token
|
raise AuthenticationError("Missing or invalid Authorization header")
|
||||||
token = headers.get("authorization", "")
|
# 白名单设备只延长 token 有效期,仍然校验 token
|
||||||
if token.startswith("Bearer "):
|
expire_seconds = None
|
||||||
token = token[7:] # 移除'Bearer '前缀
|
if self.allowed_devices and device_id in self.allowed_devices:
|
||||||
else:
|
expire_seconds = self.allowed_expire_seconds
|
||||||
raise AuthenticationError("Missing or invalid Authorization header")
|
# 进行认证
|
||||||
# 进行认证
|
auth_success = self.auth.verify_token(
|
||||||
auth_success = self.auth.verify_token(
|
token,
|
||||||
token, client_id=client_id, username=device_id
|
client_id=client_id,
|
||||||
)
|
username=device_id,
|
||||||
if not auth_success:
|
expire_seconds=expire_seconds,
|
||||||
raise AuthenticationError("Invalid token")
|
)
|
||||||
|
if not auth_success:
|
||||||
|
raise AuthenticationError("Invalid token")
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue