Api Key Exposure in Fiber with Jwt Tokens
Api Key Exposure in Fiber with Jwt Tokens — how this specific combination creates or exposes the vulnerability
When API keys are handled alongside JWT tokens in a Fiber application, the risk of exposure increases if either credential type is inadvertently surfaced to unauthorized parties. API keys are typically long-lived secrets used for service-to-service identification, while JWT tokens are often used for user authentication and authorization. In Fiber, routes and middleware can accidentally expose both types of data through verbose error messages, debug endpoints, improper logging, or misconfigured CORS and HTTP header handling.
For example, if an endpoint that validates JWT tokens also logs the raw Authorization header, an API key embedded in a service call might be written to logs or returned in a debug response. A path-based route like /api/proxy that accepts an API key as a query parameter and also decodes a JWT from the Authorization header can become a leakage point if the handler does not carefully separate and protect each credential type. Insecure direct object references (IDOR) or broken access control can further allow one token to be substituted for another, causing an API key or JWT to be used in contexts they were never intended for.
Additionally, an OpenAPI spec that defines both securitySchemes — one for an API key (in header or query) and one for a bearer JWT — might not enforce strict separation at runtime. If the Fiber server mixes required security declarations without properly validating which credential is required for which route, a client might send a JWT where an API key is expected, or omit necessary credentials, leading to unauthorized access or information leakage. Misconfigured TLS termination or missing secure flagging on cookies can also expose tokens in transit or at rest.
middleBrick detects these risks by scanning the unauthenticated attack surface of a Fiber endpoint, cross-referencing OpenAPI/Swagger definitions with runtime behavior. For each of the 12 security checks, it looks for signs that API keys and JWT tokens are being handled without adequate isolation, logging, or input validation. Findings include improper header usage, verbose errors that reveal tokens, missing rate limiting on authentication endpoints, and inconsistent authorization across routes.
Common real-world patterns that increase exposure include:
- Concatenating API keys and JWTs in logs or error payloads
- Using the same HTTP header name for different credential types across services
- Allowing unauthenticated introspection endpoints that return token metadata
- Failing to rotate or revoke compromised keys and tokens promptly
Because middleBrick tests authentication, BOLA/IDOR, Data Exposure, and Input Validation in parallel, it can identify whether a Fiber route inadvertently returns API keys or JWTs in responses, logs, or error traces, and map findings to frameworks such as OWASP API Top 10 and SOC2 controls.
Jwt Tokens-Specific Remediation in Fiber — concrete code fixes
To reduce the risk of exposing JWT tokens in a Fiber application, adopt strict separation between authentication, authorization, and service credentials, and ensure tokens are never unnecessarily echoed or logged. Use strongly typed middleware, validate token structure before processing, and avoid including sensitive material in URLs or logs.
Secure JWT validation middleware in Fiber
The following example shows a secure JWT validation middleware for Fiber that verifies the token, extracts claims, and ensures no raw Authorization header is logged. It uses github.com/golang-jwt/jwt/v5 and avoids printing sensitive values.
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/golang-jwt/jwt/v5"
)
func JWTMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
auth := c.Get("Authorization")
if auth == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "authorization header required"})
}
// Bearer
tokenString := auth[len("Bearer "):]
if tokenString == auth {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "bearer token expected"})
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// TODO: use proper key management and avoid hardcoded keys
return []byte("your-secret-key"), nil
})
if err != nil || !token.Valid {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid token"})
}
// Safely use claims without logging the raw token
if claims, ok := token.Claims.(jwt.MapClaims); ok {
c.Locals("userID", claims["sub"])
}
return c.Next()
}
}
func main() {
app := fiber.New()
app.Use(logger.New()) // ensure logger does not capture Authorization header
app.Get("/secure", JWTMiddleware(), func(c *fiber.Ctx) error {
userID := c.Locals("userID")
return c.JSON(fiber.Map{"message": "ok", "user": userID})
})
app.Listen(":3000")
}
Avoiding API key and JWT confusion in routes
Define separate route groups for different credential types and enforce security schemes explicitly. Do not allow query parameters to carry API keys when the spec expects a bearer token, and vice versa.
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/adaptor/chi"
)
func main() {
app := fiber.New()
// API key protected route group
apiKeyGroup := app.Group("/api")
apiKeyGroup.Use(apiKeyAuthMiddleware())
apiKeyGroup.Get("/data", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"data": "requires API key"})
})
// JWT protected route group
jwtGroup := app.Group("/app")
jwtGroup.Use(JWTMiddleware())
jwtGroup.Get("/profile", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"profile": "requires JWT"})
})
app.Listen(":3000")
}
func apiKeyAuthMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
key := c.Get("X-API-Key")
if key != "super-secret-key" {
return c.SendStatus(fiber.StatusForbidden)
}
return c.Next()
}
}
Operational practices to prevent exposure
- Ensure logs redact Authorization header values and do not capture full tokens
- Use distinct HTTP headers for API keys and JWTs (e.g.,
X-API-KeyvsAuthorization: Bearer) - Apply strict CORS policies and avoid exposing tokens to browser-based JavaScript unless necessary
- Rotate keys and revoke tokens promptly when compromise is suspected
middleBrick’s LLM/AI Security checks specifically test for system prompt leakage and output scanning that could expose JWTs or API keys generated or echoed by any integrated AI tooling. The scanner also flags missing rate limiting on authentication endpoints and checks for unsafe consumption patterns that might lead to token exposure.