Jwt Misconfiguration in Aspnet with Bearer Tokens
Jwt Misconfiguration in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
In ASP.NET applications, JWT validation is commonly configured to use Bearer tokens via AddJwtBearer. When this integration is misconfigured, the API accepts tokens that are missing, malformed, or overly permissive, which directly expands the unauthenticated attack surface that middleBrick scans. A typical vulnerable setup uses a non-valid issuer, permissive token validation parameters, or does not enforce HTTPS, allowing tokens issued by any trusted-signing key source to be accepted.
For example, configuring AddJwtBearer without validating the issuer and audience increases the risk of token substitution attacks, where an attacker presents a token issued for a different resource. Similarly, failing to set a short token lifetime or not enforcing token revocation mechanisms can lead to token replay or long-lived credential exposure. These misconfigurations are especially dangerous when combined with Bearer token transmission over unencrypted channels, as tokens can be intercepted and reused.
middleBrick tests such unauthenticated endpoints and flags issues like missing anti-replay protections, weak signing algorithms (e.g., none or HS256 with weak secrets), and missing scope or role claims validation. A misconfigured JWT setup can map to multiple checks within the 12 security scans, including Authentication, Authorization (BOLA/IDOR), and Data Exposure, because an attacker can leverage a malformed token to access or escalate privileges across endpoints.
Real-world attack patterns include exploiting tokens signed with the 'none' algorithm (CVE-2015-9235) or tokens using predictable signing keys. Without proper token binding and audience/issuer validation, an API may treat a token from any identity provider as valid, bypassing intended access controls. middleBrick’s OpenAPI/Swagger analysis correlates runtime behavior with spec definitions to highlight mismatches between declared security schemes and actual implementation, ensuring findings align with standards like OWASP API Top 10 and PCI-DSS.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Secure JWT validation with Bearer tokens in ASP.NET requires explicit configuration of token validation parameters, HTTPS enforcement, and audience/issuer checks. The following examples demonstrate a hardened setup that mitigates common misconfigurations.
Secure JWT Bearer Configuration (Program.cs)
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Enforce HTTPS in production-like environments
builder.Services.AddHttpsRedirection(options =>
{
options.HttpsPort = 443;
});
// Configure JWT Bearer with strict validation
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://auth.example.com",
ValidateAudience = true,
ValidAudience = "https://api.example.com",
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(2),
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"] ?? throw new InvalidOperationException("JWT secret is missing"))
),
// Recommended: restrict allowed algorithms
AllowedSigningAlgorithms = new[] { "RS256", "ES256" }
};
// Enforce HTTPS for token transmission
options.RequireHttpsMetadata = true;
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/secure", (ClaimsPrincipal user) =>
{
return Results.Ok(new { Message = $"Hello, {user.Identity?.Name ?? "Anonymous"}" });
}).RequireAuthorization();
app.Run();
Example Bearer Token Request
Clients must include the token in the Authorization header:
GET /secure HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Accept: application/json
Additional Hardening Practices
- Store signing secrets in secure configuration providers (e.g., Azure Key Vault, environment variables with restricted access).
- Set short expiration times (e.g., 15 minutes) and implement refresh token flows with strict validation.
- Validate token scopes and roles within endpoint logic to enforce least-privilege access.
- Rotate signing keys periodically and monitor for token replay using short-lived nonces or one-time tokens where applicable.
By applying these configurations, the API reduces the risk of token misuse and aligns with security best practices, which middleBrick can verify through its Authentication and Authorization checks.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |