HIGH integrity failuresaspnetbearer tokens

Integrity Failures in Aspnet with Bearer Tokens

Integrity Failures in Aspnet with Bearer Tokens — how this combination creates or exposes the vulnerability

An integrity failure occurs when an API trusts input or tokens that should have been validated or protected against tampering. In ASP.NET APIs that use Bearer Tokens, this typically manifests as accepting a token that is structurally valid but not sufficiently bound to the intended context, allowing an attacker to alter claims, escalate privileges, or impersonate another identity.

Bearer Tokens are often passed via the Authorization header as Authorization: Bearer {token}. If the server does not rigorously validate the token’s signature, issuer, audience, and scope, or if it relies on client-supplied data (such as user identifiers in URLs or bodies) without re‑verifying token‑to‑resource ownership, integrity is compromised. For example, an attacker who can modify a non‑signed claim like role or sub in a loosely validated token may gain unauthorized access to other users’ resources (BOLA/IDOR) or perform privileged actions.

ASP.NET’s JWT Bearer middleware validates signature and standard claims by default when properly configured, but developers sometimes disable or weaken these checks. Common misconfigurations include omitting ValidateIssuer and ValidateAudience, accepting any issuer, or using a weak symmetric key that is guessable or exposed. If the token validation parameters do not enforce strict issuer and audience checks, an attacker can present a token issued by a different service or for a different audience and have it accepted, leading to identity confusion and integrity failures.

Another scenario involves over‑trust in token metadata. If the API uses claims from the token to make authorization decisions without additional server‑side checks (e.g., confirming that the token’s subject maps correctly to the resource being accessed), an attacker can tamper with URL paths or request parameters to access another user’s data. This intersects with BOLA/IDOR when the API endpoint uses an identifier from the client rather than deriving the identifier from the validated token’s claims.

Insecure token storage on the client side can also lead to integrity issues. If tokens are stored in local storage or insecure cookies and are susceptible to XSS, an attacker can read or modify the token before it reaches the ASP.NET backend. Even with strong signature validation, a stolen or modified token can be replayed to perform actions on behalf of the legitimate user.

To detect these patterns, middleBrick’s LLM/AI Security checks probe for system prompt leakage and prompt injection while scanning the unauthenticated attack surface. Its API security checks validate authentication, input validation, and authorization logic, including how Bearer Tokens are verified and mapped to user contexts. By correlating spec definitions with runtime behavior, the scanner highlights missing issuer/audience validation, excessive agency patterns, and inconsistencies between documented scopes and actual enforcement.

Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes

Remediation focuses on strict token validation, binding tokens to requests, and avoiding client‑controlled authorization data. Use the built‑in JWT Bearer middleware with explicit configuration and avoid accepting unverified claims.

Ensure your ASP.NET API enforces issuer and audience validation and uses a strong, well‑protected signing key. The following example shows secure configuration in Program.cs:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "https://your-identity-provider.com",
            ValidateAudience = true,
            ValidAudience = "https://your-api-audience.com",
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT key is missing")),
            ClockSkew = TimeSpan.FromMinutes(2)
        };
    });

builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/items/{id}", (Guid id, ClaimsPrincipal user) =>
{
    // Server‑side check: ensure the token subject matches the resource
    var subClaim = user.FindFirst("sub")?.Value;
    if (string.IsNullOrEmpty(subClaim))
    {
        return Results.Forbid();
    }
    // Enforce that the subject can only access their own items
    if (!Guid.TryParse(subClaim, out var userId) || userId != id)
    {
        return Results.Forbid();
    }
    return Results.Ok(new { ItemId = id, OwnedBy = userId });
}).RequireAuthorization();

app.Run();

Store the signing key securely (e.g., Azure Key Vault, environment variables with restricted access) and rotate it periodically. Avoid accepting tokens with null or weak issuers/audiences, and explicitly set ValidateIssuer and ValidateAudience to true.

On the client side, store Bearer Tokens in secure, HTTP‑only cookies or platform‑specific secure storage, and ensure your frontend is protected against XSS to prevent token leakage or modification. Do not embed user identifiers or roles in the URL; derive them from the validated token claims on the server.

When using scopes and roles, validate them server‑side rather than trusting client‑supplied values. For example, verify that the token contains a required scope before allowing sensitive operations:

app.MapDelete("/items/{id}", (Guid id, ClaimsPrincipal user) =>
{
    if (!user.HasClaim(c => c.Type == "scope" && c.Value == "items:delete"))
    {
        return Results.Forbid();
    }
    // Proceed with deletion ensuring subject matches resource
    var sub = user.FindFirst("sub")?.Value;
    // ... deletion logic
    return Results.NoContent();
}).RequireAuthorization();

middleBrick’s CLI can be used to verify that your endpoints enforce these checks in CI/CD: middlebrick scan <url>. The Pro plan supports continuous monitoring and GitHub Action integration to fail builds if risk scores degrade, helping maintain integrity across deployments.

Frequently Asked Questions

Why is issuer and audience validation important for Bearer Token integrity in ASP.NET?
Issuer and audience validation prevent tokens issued by one service or intended for another service from being accepted. Without these checks, an attacker can present a token from a different issuer/audience and have it accepted, leading to identity confusion and privilege escalation.
How does middleBrick help detect integrity failures related to Bearer Tokens?
middleBrick runs authentication and authorization checks, input validation, and LLM/AI security probes to identify missing token validation, over‑trust in claims, and inconsistencies between OpenAPI specs and runtime behavior. Findings include severity, remediation guidance, and mapping to frameworks like OWASP API Top 10.