Pii Leakage in Chi with Jwt Tokens
Pii Leakage in Chi with Jwt Tokens — how this specific combination creates or exposes the vulnerability
Chi is a lightweight HTTP library for .NET often used to build minimal APIs. When JWT tokens are handled in Chi endpoints without strict validation and output controls, PII leakage can occur through verbose error messages, reflection, or insecure serialization. A token may carry claims such as email, name, or roles; if these are echoed back in responses or logged, PII is unintentionally exposed.
During a black-box scan, middleBrick tests unauthenticated attack surfaces and checks whether authentication mechanisms leak data. For Chi endpoints accepting JWT tokens in headers, the scanner verifies that tokens are not reflected in JSON payloads, response headers, or error traces. A common misconfiguration is returning the full ClaimsPrincipal or embedding the token payload directly into response objects, which can disclose email addresses or identifiers to unauthenticated callers.
Another leakage vector arises when middleware or exception handlers expose stack traces or configuration details that include token validation parameters. For instance, a poorly handled invalid token scenario might return a 500 response with raw exception text containing issuer, audience, or signing key hints. Even if the endpoint does not authenticate, an attacker can infer internal logic or harvest PII from verbose messages. middleBrick’s checks include Data Exposure and Authentication analyses to detect whether responses inadvertently reveal data tied to identity claims.
SSRF and unsafe consumption patterns can compound the risk. If a Chi service accepts user-controlled URLs and uses JWT-bearing outbound requests, tokens may be leaked to unintended endpoints. Similarly, insecure consumption of external schemas or reflection-based deserialization can expose claims when responses are serialized without filtering sensitive properties.
LLM/AI Security checks are especially relevant when endpoints expose AI features or chat-like interactions. Should a Chi endpoint leak system prompts or token metadata that match known LLM formats, middleBrick’s system prompt leakage detection can identify regex patterns tied to ChatML or Mistral-style templates. Combined with active prompt injection probes, this helps ensure that JWT handling does not expose instructions or data that could be exfiltrated through adversarial inputs.
Finally, the scanner correlates findings with compliance frameworks such as OWASP API Top 10 and GDPR, highlighting PII exposure as a high-severity concern. By reviewing per-category breakdowns and remediation guidance in the dashboard, teams can prioritize fixes that prevent identity data from reaching unauthorized parties.
Jwt Tokens-Specific Remediation in Chi — concrete code fixes
Remediation focuses on strict token validation, avoiding reflection of claims, and ensuring error handling does not disclose sensitive information. Below are concrete code examples using Chi that demonstrate secure handling of JWT tokens.
First, validate tokens explicitly and return generic error responses. Do not echo the token or its payload back to the client.
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Chi;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://auth.example.com",
ValidateAudience = true,
ValidAudience = "api.example.com",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("very-secret-key-256bit-long-change-in-prod"))
};
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/profile", (ClaimsPrincipal user) =>
{
// Return only necessary, non-sensitive claims
var email = user.FindFirst(System.Security.Claims.ClaimTypes.Email)?.Value;
var name = user.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value;
return new { Email = email, Name = name };
}).RequireAuthorization();
app.Run();
Second, avoid returning the full ClaimsPrincipal or token metadata. Instead, construct a minimal response object that excludes roles or identifiers not required by the client.
app.MapGet("/minimal", (ClaimsPrincipal user) =>
{
var safeResponse = new
{
IsAuthenticated = user.Identity?.IsAuthenticated ?? false,
Name = user.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value
};
return Results.Ok(safeResponse);
});
Third, ensure exceptions during token validation do not leak internal details. Use centralized error handling that masks stack traces while logging details securely.
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
await context.Response.WriteAsJsonAsync(new { Error = "An error occurred." });
});
});
With these practices, Chi services can safely handle JWT tokens while minimizing PII leakage. middleBrick’s scans verify that responses do not contain sensitive claims and that authentication mechanisms are robust, helping teams align with security and compliance expectations.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |