fix(auth): JWT 中间件支持 query parameter token 回退
SSE/EventSource 无法设置自定义 Authorization 头,前端通过 ?token=xxx 传参。中间件现在优先读 Authorization 头,回退到 URL query parameter,修复 SSE 连接永远 401 的问题。
This commit is contained in:
@@ -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=xxx(SSE/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" {
|
||||
|
||||
Reference in New Issue
Block a user