@@ -12,27 +12,39 @@ import (
1212// AuthMiddleware JWT 认证中间件
1313func AuthMiddleware (authService * auth.Service ) gin.HandlerFunc {
1414 return func (c * gin.Context ) {
15- // 从 Authorization header 中提取 token
15+ // 优先从 Authorization header 中提取 token
1616 authHeader := c .GetHeader ("Authorization" )
17- if authHeader == "" {
18- c .JSON (http .StatusUnauthorized , gin.H {
19- "error" : "Missing authorization header" ,
20- })
21- c .Abort ()
22- return
23- }
17+ token := ""
2418
25- // 检查格式:Bearer <token>
26- parts := strings .SplitN (authHeader , " " , 2 )
27- if len (parts ) != 2 || parts [0 ] != "Bearer" {
28- c .JSON (http .StatusUnauthorized , gin.H {
29- "error" : "Invalid authorization header format. Expected: Bearer <token>" ,
30- })
31- c .Abort ()
32- return
33- }
19+ if authHeader != "" {
20+ // 检查格式:Bearer <token>
21+ parts := strings .SplitN (authHeader , " " , 2 )
22+ if len (parts ) != 2 || parts [0 ] != "Bearer" {
23+ c .JSON (http .StatusUnauthorized , gin.H {
24+ "error" : "Invalid authorization header format. Expected: Bearer <token>" ,
25+ })
26+ c .Abort ()
27+ return
28+ }
29+
30+ token = parts [1 ]
31+ } else {
32+ // WebSocket / SSE 在浏览器端无法方便地自定义 Authorization header,
33+ // 允许仅对 /api/ws/* 与 /api/sse/* 使用 query 参数透传 token。
34+ path := c .Request .URL .Path
35+ if c .Request .Method == http .MethodGet &&
36+ (strings .HasPrefix (path , "/api/ws/" ) || strings .HasPrefix (path , "/api/sse/" )) {
37+ token = c .Query ("token" )
38+ }
3439
35- token := parts [1 ]
40+ if token == "" {
41+ c .JSON (http .StatusUnauthorized , gin.H {
42+ "error" : "Missing authorization header" ,
43+ })
44+ c .Abort ()
45+ return
46+ }
47+ }
3648
3749 // 验证 token
3850 username , err := authService .ValidateToken (token )
0 commit comments