fix(auth): JWT 中间件支持 query parameter token 回退
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / security-audit (push) Has been cancelled

SSE/EventSource 无法设置自定义 Authorization 头,前端通过
?token=xxx 传参。中间件现在优先读 Authorization 头,回退到
URL query parameter,修复 SSE 连接永远 401 的问题。
This commit is contained in:
iven
2026-04-28 11:23:53 +08:00
parent c556bda82b
commit 988f6cd6a5

View File

@@ -39,18 +39,25 @@ pub async fn jwt_auth_middleware_fn(
req: Request<Body>,
next: Next,
) -> Result<Response, AppError> {
let auth_header = req
// 优先从 Authorization 头提取 token
// 回退到 URL query parameter ?token=xxxSSE/EventSource 无法设置自定义头)
let token = req
.headers()
.get("Authorization")
.and_then(|v| v.to_str().ok())
.ok_or(AppError::Unauthorized)?;
let token = auth_header
.strip_prefix("Bearer ")
.and_then(|h| h.strip_prefix("Bearer "))
.map(String::from)
.or_else(|| {
req.uri().query().and_then(|q| {
q.split('&')
.find_map(|pair| pair.strip_prefix("token="))
.map(String::from)
})
})
.ok_or(AppError::Unauthorized)?;
let claims =
TokenService::decode_token(token, &jwt_secret).map_err(|_| AppError::Unauthorized)?;
TokenService::decode_token(&token, &jwt_secret).map_err(|_| AppError::Unauthorized)?;
// Verify this is an access token, not a refresh token
if claims.token_type != "access" {