跨域回显来源并清理示例白名单

跨域以前固定回 *,同时又允许带凭证,浏览器会直接拦下。改成回显具体
来源,默认还是放开所有来源,运维想收紧就填具体地址。config.yaml 里
顺手清了示例白名单地址 —— 那是公开可知的,用户只开认证开关就会白白
继承一条谁都能冒充的白名单;顺便补上新配置项的说明。
This commit is contained in:
hrz 2026-10-22 01:26:21 +00:00
parent f87b1b0460
commit 0b5a0097cd
2 changed files with 39 additions and 7 deletions

View file

@ -32,9 +32,25 @@ server:
# 是否启用认证
enabled: false
# 白名单设备ID列表
# 如果属于白名单内的设备,不校验token,直接放行
allowed_devices:
- "11:22:33:44:55:66"
# 命中白名单只延长该设备 token 的有效期,不再跳过 token 校验
# 格式为设备上报的 Device-Id(MAC),例如 "aa:bb:cc:dd:ee:ff"
# 不要把 Client-Id 填进来:它是 UUID v4,擦 FLASH 或重装后会变化,
# 当长期标识会导致设备直接被锁在门外
allowed_devices: []
# 白名单设备的 token 有效期(秒)。留空表示与 expire_seconds 一致,
# 不因进白名单就放宽;确有需要时可设置,但上限建议 90 天
allowed_devices_expire_seconds: null
# 一次性激活码,供没有 token 的设备首次接入时换取 token,用掉即失效
# 新设备接入流程:在此列表中预先加入一个码,设备带着该码请求 OTA 接口,
# 服务端签发 token 后自动从列表移除该码
activation_codes: []
# token 签发时刻下界(Unix 秒)。改成当前时间即可一次性作废所有存量 token,
# 设备下次开机请求 OTA 时会自动换发新 token,无需维护黑名单
issued_after: 0
# CORS 允许的来源列表。默认 ["*"] 表示回显任意来源的 Origin;
# 收紧时填具体来源,例如 ["https://your-console.example.com"]
cors:
allowed_origins: ["*"]
# MQTT网关配置,用于通过OTA下发到设备,根据mqtt_gateway的.env文件配置,格式为host:port
mqtt_gateway: null
# MQTT签名密钥,用于生成MQTT连接密码,根据mqtt_gateway的.env文件配置

View file

@ -7,18 +7,34 @@ class BaseHandler:
self.config = config
self.logger = setup_logging()
def _add_cors_headers(self, response):
def _resolve_cors_origin(self, origin: str | None) -> str | None:
"""回显允许的 Origin,取不到或不在名单里时不放 CORS 头"""
if not origin:
return None
cors = self.config.get("server", {}).get("cors", {}) or {}
allowed = cors.get("allowed_origins", ["*"]) or ["*"]
if "*" in allowed:
return origin
return origin if origin in allowed else None
def _add_cors_headers(self, response, request=None):
"""添加CORS头信息"""
response.headers["Access-Control-Allow-Headers"] = (
"client-id, content-type, device-id, authorization"
)
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Access-Control-Allow-Origin"] = "*"
origin = self._resolve_cors_origin(
request.headers.get("Origin") if request is not None else None
)
if origin:
# 回显具体 Origin,配合 Allow-Credentials 才是浏览器规范允许的写法
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Vary"] = "Origin"
async def handle_options(self, request):
"""处理OPTIONS请求,添加CORS头信息"""
response = web.Response(body=b"", content_type="text/plain")
self._add_cors_headers(response)
self._add_cors_headers(response, request)
# 添加允许的方法
response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
return response