Xss Cross Site Scripting in Fiber with Jwt Tokens
Xss Cross Site Scripting in Fiber with Jwt Tokens — how this specific combination creates or exposes the vulnerability
Cross-site scripting (XSS) in a Fiber application that uses JWT tokens can occur when an API returns user-controlled data inside a response that is later rendered in a browser without proper escaping. Even though JWTs themselves are cryptographically signed and encoded, they often carry claims such as name, email, or other identifiers that may be displayed in a UI. If these claims are inserted into HTML, attributes, or JavaScript without sanitization, reflected or stored XSS can result. A typical pattern is an endpoint that decodes a JWT, extracts a claim, and embeds it in an HTML template or returns it as part of a JSON payload that a frontend framework renders unsafely. Because XSS is a client-side injection issue, the vulnerability resides in how the application uses data from the JWT, not in the token format.
Another relevant risk involves APIs that expose endpoints accepting an Authorization header with a Bearer JWT while also reflecting user input or metadata in responses. For example, an endpoint might include the subject or username from the JWT in a JSON response that a single-page application renders directly via innerHTML or a similar unsafe DOM operation. Even though the JWT validates identity, trusting its claims for output without escaping creates an XSS surface. In security scans, this shows as improper output encoding in the context of authenticated requests. The scan’s Authentication and Input Validation checks help surface cases where JWT-derived data is used in reactive contexts without safe handling.
Consider a scenario where a Fiber handler decodes a JWT and uses a claim to personalize a response that includes HTML. If the developer writes the claim directly into a template without escaping, an attacker could supply a malicious payload as part of their identity (e.g., during registration or profile update) and have it executed in other users’ browsers. Because the API appears to be properly authenticated, developers might overlook output encoding, assuming JWT integrity prevents tampering. However, integrity does not imply safety for rendering. The LLM/AI Security checks are not relevant here, but the broader testing for Input Validation and Data Exposure helps identify places where attacker-controlled data reaches outputs that involve HTML or script contexts.
Jwt Tokens-Specific Remediation in Fiber — concrete code fixes
To remediate XSS when using JWT tokens in Fiber, ensure any data derived from JWT claims is properly encoded for the context where it is used. For HTML body content, use HTML escaping; for attributes, use attribute escaping; and for JavaScript, avoid inline evaluation or use safe serialization. Below are concrete code examples for a Fiber handler that decodes a JWT and safely uses its claims.
// Safe HTML rendering with escaped JWT claims
package main
import (
"html"r> "github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
)
func main() {
app := fiber.New()
app.Get("/profile", func(c *fiber.Ctx) error {
tokenString := c.Get("Authorization")
if tokenString == "" {
return c.Status(fiber.StatusUnauthorized).SendString("Missing token")
}
// Remove "Bearer " prefix if present
if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
tokenString = tokenString[7:]
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// TODO: provide your key and validation logic
return []byte("your-secret"), nil
})
if err != nil || !token.Valid {
return c.Status(fiber.StatusUnauthorized).SendString("Invalid token")
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// Safely escape any claim used in HTML
name := html.EscapeString(claims["name"].(string))
email := html.EscapeString(claims["email"].(string))
c.SetType("text/html")
return c.SendString("Name: " + name + "Email: " + email + "")
}
return c.Status(fiber.StatusInternalServerError).SendString("Invalid claims")
})
app.Listen(":3000")
}
For JSON responses, ensure the frontend does not use unsafe rendering patterns. If you return JSON that will be rendered by JavaScript, do not rely on the API to prevent XSS; instead, the client must avoid inserting untrusted data using innerHTML. Still, you can reduce risk by validating and sanitizing input claims and by not reflecting raw user-controlled data in contexts that can execute script.
When integrating with the middleBrick CLI, you can run middlebrick scan <url> to detect XSS-related findings in your endpoints, including those that handle authenticated requests with JWTs. The dashboard and GitHub Action integrations can help you track these findings over time and fail builds if risk scores degrade. Remediation guidance from scans will point to specific places where JWT-derived data reaches outputs without proper encoding.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |