HIGH insecure deserializationaspnetbearer tokens

Insecure Deserialization in Aspnet with Bearer Tokens

Insecure Deserialization in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Insecure deserialization occurs when an application processes untrusted serialized data without sufficient validation. In ASP.NET applications, this commonly manifests through the deserialization of attacker-controlled payloads, for example in custom token handlers or when processing JSON/XML configuration tied to authentication. Bearer tokens are often used for API authentication; if a token’s claims or its compact representation are deserialized insecurely, an attacker can manipulate the payload to execute arbitrary code, escalate privileges, or bypass authorization checks.

Consider an ASP.NET Core API that uses a custom JWT handler with additional encrypted claims. If the application uses insecure deserialization (e.g., BinaryFormatter, XmlSerializer with dangerous type resolution, or poorly implemented custom converters) on data derived from the token, an attacker can embed malicious serialized objects. Upon deserialization server-side, this can lead to remote code execution (RCE), object graph manipulation, or authentication bypass. Real-world patterns include gadgets chains leveraging types such as System.Web.UI.ObjectStateFormatter or unsafe polymorphic deserialization in custom claim transformers. This becomes especially dangerous when combined with Bearer tokens because the token is often automatically attached by clients and may be accepted without strict schema validation, allowing an attacker to slip malicious payloads inside the token’s serialized structure.

Even when the token itself is cryptographically signed, the application may deserialize portions of the token or related session data separately. For instance, storing server-side session state keyed by a deserialized version of the token’s claims can open the door to gadget-based exploits. Common frameworks and libraries used with ASP.NET may introduce unsafe defaults; for example, older versions of Newtonsoft.Json with TypeNameHandling enabled can allow type injection if the application deserializes JSON from token-derived data without strict type constraints. Attack patterns tracked in the OWASP API Top 10 align with this risk, and real CVEs such as CVE-2021-44228-style logic can manifest when deserialization is improperly scoped to authentication material.

In black-box scanning with middleBrick, the tool tests the unauthenticated attack surface and can surface indicators of insecure deserialization in API responses or documentation-defined endpoints that process serialized data. Because no agents or credentials are required, the scanner can identify risky behaviors—such as verbose errors revealing gadget chains or endpoints that accept serialized blobs—without access to production data. Developers should treat Bearer tokens as opaque credentials and avoid tying deserialization logic to token-derived content unless strict schema validation and allowlists are enforced.

To detect such issues, security checks examine the API surface for dangerous deserialization routines, input validation gaps, and improper error handling. middleBrick runs 12 security checks in parallel, including Input Validation and Property Authorization, to highlight where untrusted data—potentially originating from token claims—enters the object graph. This ensures findings are tied directly to the application’s authentication patterns while providing prioritized remediation guidance aligned with compliance frameworks like OWASP API Top 10 and SOC2.

Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes

Remediation focuses on eliminating unsafe deserialization and strictly validating Bearer token content. Do not deserialize data of attacker-controlled origin; if you must, use safe serializers with type allowlists and disable polymorphic resolution. For JWTs, validate the signature, audience, issuer, and enforce strict claim schemas. Below are concrete code examples for ASP.NET Core that demonstrate secure handling of Bearer tokens.

1. Avoid dangerous deserialization; prefer structured models

Instead of deserializing token payloads with risky formatters, bind claims to defined models and validate explicitly. This prevents gadget chains and type injection.

// BAD: Avoid if token content is used in deserialization
// var result = JsonConvert.DeserializeObject(userData, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });

// GOOD: Use strict DTOs and validate claims
public class TokenClaims
{
    public string Sub { get; set; }
    public string Role { get; set; }
    public string Scope { get; set; }
}

public TokenClaims ValidateAndExtractClaims(string token)
{
    var handler = new JwtSecurityTokenHandler();
    var validationParams = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = "https://auth.example.com",
        ValidateAudience = true,
        ValidAudience = "api.example.com",
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VeryStrongKeyAtLeast32BytesLong!!")),
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };

    SecurityToken validated;
    var principal = handler.ValidateToken(token, validationParams, out validated);
    var jwt = validated as JwtSecurityToken;
    var claims = new TokenClaims
    {
        Sub = jwt.Subject,
        Role = jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value,
        Scope = jwt.Claims.FirstOrDefault(c => c.Type == "scope")?.Value
    };
    return claims;
}

2. Secure JSON settings for any remaining serialization

If you must serialize/deserialize user data, disable polymorphic type resolution and use contract resolver settings that ignore TypeNameHandling.

var settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.None,
    MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
var safeObject = JsonConvert.DeserializeObject<MyDataContract>(json, settings);

3. Enforce strict schema validation for token-derived data

Treat Bearer tokens as opaque strings; do not embed serialized objects inside them. If you store session data server-side, key it by a verified subject identifier and validate against a strict schema before use.

// Example of strict claim validation without unsafe deserialization
var requiredClaims = new[] { "sub", "exp", "iss", "scope" };
foreach (var claim in requiredClaims)
{
    if (string.IsNullOrEmpty(user.FindFirst(claim)?.Value))
    {
        throw new SecurityTokenInvalidClaimsException($"Missing required claim: {claim}");
    }
}

4. Use middleware to reject malformed tokens early

Configure the JWT Bearer middleware to fail securely on invalid tokens and avoid fallback paths that might trigger unsafe processing.

// In Startup.cs or Program.cs
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://auth.example.com";
        options.Audience = "api.example.com";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "https://auth.example.com",
            ValidAudience = "api.example.com",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VeryStrongKeyAtLeast32BytesLong!!"))
        };
        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                // Keep token acquisition explicit; avoid automatic extraction from insecure locations
                var token = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
                if (!string.IsNullOrEmpty(token))
                {
                    context.Token = token;
                }
                return Task.CompletedTask;
            }
        };
    });

By combining these practices—opaque token handling, strict schema validation, and safe serializers—you reduce the attack surface for insecure deserialization when Bearer tokens are involved. middleBrick’s scans can help verify that endpoints do not rely on unsafe deserialization patterns and that error messages do not leak gadget chains.

Frequently Asked Questions

Does middleBrick fix deserialization vulnerabilities in my API?
middleBrick detects and reports insecure deserialization patterns and provides remediation guidance, but it does not automatically fix or patch your code. Apply the suggested secure coding practices and validate changes through testing.
Can Bearer tokens contain serialized objects safely?
Avoid embedding serialized objects inside Bearer tokens. Treat tokens as opaque credentials, validate signatures and claims strictly, and do not perform unsafe deserialization on any data derived from tokens.