Open Redirect in Fiber with Jwt Tokens
Open Redirect in Fiber with Jwt Tokens — how this specific combination creates or exposes the vulnerability
An open redirect in a Fiber application that uses JWT tokens can occur when a redirect target is derived from attacker-controlled data and the application relies on JWT-based session handling or token-passing flows without strict validation. For example, a common pattern is to redirect users after authentication, passing a JWT token or a return URL in query parameters. If the server uses an untrusted value for the redirect location—such as a next or redirect_to parameter—and does not enforce an allowlist of trusted origins, an attacker can craft a URL like https://api.example.com/login?redirect_to=https://evil.com. After successful authentication, the server issues a JWT token in a cookie or response body and then redirects to the attacker-controlled URL, causing the browser to navigate away and potentially leak the token in logs or referrers.
Specifically with JWT tokens, the risk is compounded when tokens are passed as URL fragments or query parameters during the redirect flow. If the server embeds a JWT in the redirect response (e.g., as a query parameter like https://client.example.com/callback#token=xxx) and does not validate the destination, an attacker can phish users by constructing malicious links that lead to credential or token leakage. Even if the JWT is stored in an HttpOnly cookie, an open redirect can still be used to abuse trust in the domain—for instance, by leading users to a lookalike site that hosts malicious JavaScript to harvest tokens from URLs. This pattern aligns with common OWASP API Top 10 API1:2023 security risks where untrusted redirects facilitate phishing and token theft.
In a black-box scan, middleBrick tests such flows by probing common redirect parameters and inspecting whether the response leads to an external domain without validation. This combines the unauthenticated attack surface testing of Fiber endpoints with JWT-aware payloads to detect whether tokens or sessions can be manipulated via open redirects. Because the scan runs 12 security checks in parallel—including Input Validation, Authentication, and Unsafe Consumption—it can identify cases where redirect logic interacts insecurely with JWT handling, producing findings with severity ratings and remediation guidance mapped to compliance frameworks.
Jwt Tokens-Specific Remediation in Fiber — concrete code fixes
To remediate open redirect risks in Fiber when JWT tokens are used, enforce strict allowlisting of redirect targets and avoid injecting JWTs into redirect URLs. Below are concrete, working Fiber examples in Go that demonstrate secure patterns.
1. Validate redirect targets with an allowlist
Never use raw user input for the redirect location. Instead, parse the request, check against a predefined set of trusted hosts or paths, and default to a safe location.
package main
import (
"net/url"
"github.com/gofiber/fiber/v2"
)
var allowedRedirectHosts = map[string]bool{
"https://app.example.com": true,
"https://dashboard.example.com": true,
}
func safeRedirect(c *fiber.Ctx) error {
target := c.Query("redirect_to", "https://app.example.com/home")
parsed, err := url.Parse(target)
if err != nil || !allowedRedirectHosts[parsed.Scheme+"://"+parsed.Host] {
target = "https://app.example.com/home"
}
return c.Redirect(target)
}
func main() {
app := fiber.New()
app.Get("/login", func(c *fiber.Ctx) error {
// Simulate successful auth; issue JWT as HttpOnly cookie
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiMSJ9.signature"
c.Cookie("token", token, &fiber.CookieOptions{
HTTPOnly: true,
Secure: true,
SameSite: fiber.CookieSameSiteStrictMode,
})
return safeRedirect(c)
})
app.Listen(":3000")
}
2. Avoid embedding JWTs in redirect URLs; use short-lived tokens and secure cookies
Do not pass JWTs as query parameters or URL fragments. Store tokens in secure, HttpOnly cookies and use opaque session references if needed. If you must pass state, use short-lived, single-use codes mapped server-side.
package main
import (
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
func loginHandler(c *fiber.Ctx) error {
// Validate credentials, then set a secure JWT in an HttpOnly cookie
jwt := generateJWT("user-123")
c.Cookie("auth_token", jwt, &fiber.CookieOptions{
Path: "/",
Expires: time.Now().Add(15 * time.Minute),
HTTPOnly: true,
Secure: true,
SameSite: fiber.CookieSameSiteLaxMode,
Domain: "example.com",
})
// Always redirect to a known safe path; do not use user input
return c.Redirect("/dashboard")
}
func generateJWT(subject string) string {
// In practice, use a proper JWT library (e.g., github.com/golang-jwt/jwt)
return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ9.signature"
}
func main() {
app := fiber.New()
app.Use(cors.New(cors.Config{
AllowOrigins: "https://app.example.com, https://dashboard.example.com",
AllowMethods: "GET,POST",
}))
app.Post("/auth/login", loginHandler)
app.Get("/dashboard", func(c *fiber.Ctx) error {
token := c.Cookies("auth_token")
if token == "" {
return c.Status(fiber.StatusUnauthorized).SendString("Unauthorized")
}
// Validate token via middleware; for illustration, assume valid
return c.SendString("Welcome to the dashboard")
})
app.Listen(":3000")
}
3. Use middleware to sanitize inputs and enforce HTTPS
Add middleware that normalizes and validates URLs, ensuring that any redirect logic rejects non-allowlisted hosts and enforces HTTPS.
func validateRedirect(next fiber.Handler) fiber.Handler {
return func(c *fiber.Ctx) error {
if loc := c.Get("Referer"); loc != "" {
parsed, err := url.Parse(loc)
if err != nil || !allowedRedirectHosts[parsed.Scheme+"://"+parsed.Host] {
return c.Status(fiber.StatusBadRequest).SendString("Invalid redirect target")
}
}
return next(c)
}
}
func main() {
app := fiber.New()
app.Get("/login", validateRedirect, func(c *fiber.Ctx) error {
// Safe to proceed with redirect after validation
return c.Redirect("https://app.example.com/home")
})
app.Listen(":3000")
}