APIKeyAuth returns Gin middleware that validates the X-API-Key header against the configured secret using a constant-time comparison.
()
| 87 | // APIKeyAuth returns Gin middleware that validates the X-API-Key header |
| 88 | // against the configured secret using a constant-time comparison. |
| 89 | func APIKeyAuth() gin.HandlerFunc { |
| 90 | return func(c *gin.Context) { |
| 91 | secret := apiSecretCopy() |
| 92 | if len(secret) < MinAPISecretKeyBytes { |
| 93 | httperr.Abort(c, http.StatusServiceUnavailable, "API secret key not configured") |
| 94 | return |
| 95 | } |
| 96 | apiKey := c.GetHeader("X-API-Key") |
| 97 | if constantTimeAPIKeyEqual(apiKey, secret) { |
| 98 | c.Next() |
| 99 | return |
| 100 | } |
| 101 | httperr.Abort(c, http.StatusUnauthorized, "Unauthorized") |
| 102 | } |
| 103 | } |