Skip to content

Commit 76ea22c

Browse files
committed
feat: 添加 Bearer 认证检查到插件路由
1 parent 8898847 commit 76ea22c

1 file changed

Lines changed: 21 additions & 1 deletion

File tree

astrbot/dashboard/server.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,10 @@ def __init__(
157157
self._init_jwt_secret()
158158

159159
async def srv_plug_route(self, subpath, *args, **kwargs):
160-
"""插件路由"""
160+
"""插件路由(需要认证)"""
161+
auth_error = self._require_bearer_auth()
162+
if auth_error is not None:
163+
return auth_error
161164
output = await self._dispatch_plugin_route(subpath, *args, **kwargs)
162165
if output is not None:
163166
return self._build_sdk_plugin_response(output)
@@ -241,6 +244,23 @@ def _build_sdk_plugin_response(output: dict) -> QuartResponse:
241244
response.headers[str(key)] = str(value)
242245
return response
243246

247+
def _require_bearer_auth(self):
248+
"""检查 Bearer token,无效时返回 401 响应,有效时返回 None。"""
249+
token = request.headers.get("Authorization")
250+
if not token:
251+
r = jsonify(Response().error("未授权").__dict__)
252+
r.status_code = 401
253+
return r
254+
token = token.removeprefix("Bearer ")
255+
try:
256+
payload = jwt.decode(token, self._jwt_secret, algorithms=["HS256"])
257+
g.username = payload["username"]
258+
except (jwt.InvalidTokenError, KeyError):
259+
r = jsonify(Response().error("未授权").__dict__)
260+
r.status_code = 401
261+
return r
262+
return None
263+
244264
async def auth_middleware(self):
245265
if not request.path.startswith("/api"):
246266
return None

0 commit comments

Comments
 (0)