MCPcopy
hub / github.com/marmotedu/iam / AuthFunc

Method AuthFunc

internal/pkg/middleware/auth/cache.go:49–105  ·  view source on GitHub ↗

AuthFunc defines cache strategy as the gin authentication middleware.

()

Source from the content-addressed store, hash-verified

47
48// AuthFunc defines cache strategy as the gin authentication middleware.
49func (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

Callers

nothing calls this directly

Calls 6

KeyExpiredFunction · 0.85
SetMethod · 0.80
NextMethod · 0.80
GetMethod · 0.65
ErrorfMethod · 0.65
ErrorMethod · 0.65

Tested by

no test coverage detected