Browse Source

fix check length bug

Paul 6 years ago
parent
commit
1a13e1c53e
1 changed files with 15 additions and 18 deletions
  1. 15
    18
      middleware/auth/optional_auth.go

+ 15
- 18
middleware/auth/optional_auth.go View File

1
 package auth
1
 package auth
2
 
2
 
3
 import (
3
 import (
4
-	"fmt"
5
 	"net/http"
4
 	"net/http"
6
 
5
 
6
+	"fmt"
7
 	"github.com/dgrijalva/jwt-go"
7
 	"github.com/dgrijalva/jwt-go"
8
 	"github.com/gin-gonic/gin"
8
 	"github.com/gin-gonic/gin"
9
 )
9
 )
21
 			tokenFromHeader = "Bearer " + tokenFromCookie
21
 			tokenFromHeader = "Bearer " + tokenFromCookie
22
 		}
22
 		}
23
 
23
 
24
-		if len(tokenFromHeader) < 8 {
25
-			ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
26
-			return
27
-		}
24
+		if len(tokenFromHeader) > 7 {
25
+			token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
26
+				if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
27
+					return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
28
+				}
28
 
29
 
29
-		token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
30
-			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
31
-				return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
32
-			}
30
+				return []byte(authKey), nil
31
+			})
33
 
32
 
34
-			return []byte(authKey), nil
35
-		})
36
-
37
-		if err != nil || !token.Valid {
38
-			return
39
-		}
33
+			if err != nil || !token.Valid {
34
+				return
35
+			}
40
 
36
 
41
-		if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
42
-			if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
43
-				ctx.Set(CtxRequestHeaderUserId, int64(uid))
37
+			if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
38
+				if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
39
+					ctx.Set(CtxRequestHeaderUserId, int64(uid))
40
+				}
44
 			}
41
 			}
45
 		}
42
 		}
46
 	}
43
 	}