Missing Tls in Fiber with Jwt Tokens
Missing Tls in Fiber with Jwt Tokens — how this specific combination creates or exposes the vulnerability
Transport Layer Security (TLS) ensures confidentiality and integrity between clients and servers. When a Fiber-based API that issues or validates JWT tokens does not enforce TLS, tokens can be intercepted in transit. This is especially critical because JWT tokens typically contain identity claims and are often used as bearer credentials. Without TLS, an attacker on the network can perform passive sniffing or active man-in-the-middle to capture tokens, leading to token replay and unauthorized access.
In a black-box scan, middleBrick tests unauthenticated endpoints and checks whether sensitive flows occur over unencrypted channels. For a Fiber endpoint that accepts or returns JWT tokens, missing TLS means tokens are exposed as cleartext. This violates secure transmission principles and maps to common weaknesses such as CWE-319 (Cleartext Transmission of Sensitive Information). The risk is compounded when tokens are passed in URLs or non-HTTPS headers, as they can be logged in server, proxy, or browser histories.
Consider a typical login flow: a client sends credentials to a Fiber route, receives a JWT, and then uses that JWT in an Authorization header for subsequent requests. If the login route or any token-bearing route lacks TLS, the initial token is exposed, and any downstream service that relies on that token is also compromised. Even if a subset of routes enforces HTTPS, inconsistent TLS configuration can allow leakage via mixed-content redirects or misconfigured virtual hosts.
middleBrick’s checks include verifying that authentication and token-related endpoints are served over encrypted channels. The tool flags scenarios where JWT issuance or validation occurs without TLS, providing findings that reference the unauthenticated attack surface tested. This aligns with the broader OWASP API Top 10 category for security misconfiguration and the need to enforce transport security for all token-handling paths.
Real-world implications are severe: captured JWTs can be reused until expiration, and if tokens contain high privileges, the attacker gains immediate access. Because tokens are cryptographically signed but not encrypted, their contents are visible once intercepted, exposing user identity and potentially roles or scopes embedded in the claims.
Jwt Tokens-Specific Remediation in Fiber — concrete code fixes
Remediation focuses on ensuring every request path involving JWT tokens uses TLS. In practice, this means terminating TLS at the edge (load balancer or reverse proxy) and configuring Fiber to only accept secure origins. Below are concrete Go examples that demonstrate proper setup.
First, a minimal Fiber app that issues a JWT over HTTPS. Note the use of tls.Config with certificates, and the redirect from HTTP to HTTPS to prevent accidental cleartext usage.
// main.go
package main
import (
"crypto/tls"
"log"
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/golang-jwt/jwt/v5"
)
var jwtSecret = []byte("super-secret-key")
func generateToken(username string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": username,
"exp": 1735689600,
})
return token.SignedString(jwtSecret)
}
func main() {
app := fiber.New()
app.Use(logger.New())
app.Post("/login", func(c *fiber.Ctx) error {
var creds struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.BodyParser(&creds); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid request"})
}
token, err := generateToken(creds.Username)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "could not generate token"})
}
return c.JSON(fiber.Map{"token": token})
})
// Enforce HTTPS by redirecting HTTP to HTTPS
go func() {
http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
}))
}()
server := &http.Server{
Addr: ":443",
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
}
log.Fatal(server.ListenAndServeTLS("cert.pem", "key.pem"))
}
Second, a client example that ensures JWT transmission occurs only over verified HTTPS connections. This demonstrates how to enforce TLS in the client and avoid insecure requests.
// client.go
package main
import (
"crypto/tls"
"log"
"net/http"
"github.com/gofiber/fiber/v2"
)
func main() {
transport := &http.Transport{
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
}
client := &http.Client{Transport: transport}
req, _ := http.NewRequest("POST", "https://api.example.com/login", nil)
// Add appropriate headers and body as needed
resp, err := client.Do(req)
if err != nil {
log.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
app := fiber.New()
app.Get("/protected", func(c *fiber.Ctx) error {
token := c.Get("Authorization")
// Validate token and respond
return c.SendString("protected")
})
// Use the custom HTTP client for outbound calls if making requests to other services
_ = app.Static("/", "./static")
log.Fatal(app.Listen(":3000"))
}
These examples ensure JWT tokens are always transmitted over TLS, mitigating interception risks. Additionally, validate and store tokens securely on the client side, and set short expiration times to limit the impact of token leakage. middleBrick can verify that your endpoints enforce TLS and flag any JWT-related routes served without encryption.
Related CWEs: encryption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-319 | Cleartext Transmission of Sensitive Information | HIGH |
| CWE-295 | Improper Certificate Validation | HIGH |
| CWE-326 | Inadequate Encryption Strength | HIGH |
| CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | HIGH |
| CWE-328 | Use of Weak Hash | HIGH |
| CWE-330 | Use of Insufficiently Random Values | HIGH |
| CWE-338 | Use of Cryptographically Weak PRNG | MEDIUM |
| CWE-693 | Protection Mechanism Failure | MEDIUM |
| CWE-757 | Selection of Less-Secure Algorithm During Negotiation | HIGH |
| CWE-261 | Weak Encoding for Password | HIGH |