AuthFunc defines cache strategy as the gin authentication middleware.
()
| 47 | |
| 48 | // AuthFunc defines cache strategy as the gin authentication middleware. |
| 49 | func (cache CacheStrategy) AuthFunc() gin.HandlerFunc { |
| 50 | return func(c *gin.Context) { |
| 51 | header := c.Request.Header.Get("Authorization") |
| 52 | if len(header) == 0 { |
| 53 | core.WriteResponse(c, errors.WithCode(code.ErrMissingHeader, "Authorization header cannot be empty."), nil) |
| 54 | c.Abort() |
| 55 | |
| 56 | return |
| 57 | } |
| 58 | |
| 59 | var rawJWT string |
| 60 | // Parse the header to get the token part. |
| 61 | fmt.Sscanf(header, "Bearer %s", &rawJWT) |
| 62 | |
| 63 | // Use own validation logic, see below |
| 64 | var secret Secret |
| 65 | |
| 66 | claims := &jwt.MapClaims{} |
| 67 | // Verify the token |
| 68 | parsedT, err := jwt.ParseWithClaims(rawJWT, claims, func(token *jwt.Token) (interface{}, error) { |
| 69 | // Validate the alg is HMAC signature |
| 70 | if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { |
| 71 | return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) |
| 72 | } |
| 73 | |
| 74 | kid, ok := token.Header["kid"].(string) |
| 75 | if !ok { |
| 76 | return nil, ErrMissingKID |
| 77 | } |
| 78 | |
| 79 | var err error |
| 80 | secret, err = cache.get(kid) |
| 81 | if err != nil { |
| 82 | return nil, ErrMissingSecret |
| 83 | } |
| 84 | |
| 85 | return []byte(secret.Key), nil |
| 86 | }) |
| 87 | if err != nil || !parsedT.Valid { |
| 88 | core.WriteResponse(c, errors.WithCode(code.ErrSignatureInvalid, err.Error()), nil) |
| 89 | c.Abort() |
| 90 | |
| 91 | return |
| 92 | } |
| 93 | |
| 94 | if KeyExpired(secret.Expires) { |
| 95 | tm := time.Unix(secret.Expires, 0).Format("2006-01-02 15:04:05") |
| 96 | core.WriteResponse(c, errors.WithCode(code.ErrExpired, "expired at: %s", tm), nil) |
| 97 | c.Abort() |
| 98 | |
| 99 | return |
| 100 | } |
| 101 | |
| 102 | c.Set(middleware.UsernameKey, secret.Username) |
| 103 | c.Next() |
| 104 | } |
| 105 | } |
| 106 |