Broken Authentication in Aspnet with Mongodb
Broken Authentication in Aspnet with Mongodb — how this specific combination creates or exposes the vulnerability
Broken Authentication in an ASP.NET application using MongoDB typically arises when session handling, credential storage, or token validation logic is implemented insecurely. Common patterns include storing sensitive authentication data in predictable client-side cookies, failing to enforce strong password policies, or not properly validating identity claims after a successful MongoDB query.
When ASP.NET relies on MongoDB for user management, misconfigured or incomplete authentication flows can expose the system to credential theft, session fixation, or privilege escalation. For example, if an application retrieves a user document by username without enforcing case-sensitive comparison or proper indexing, it may inadvertently allow username enumeration. If the application stores passwords using weak hashing (e.g., unsalted MD5 or SHA1) or uses reversible encryption, an attacker who gains read access to the MongoDB collection can recover credentials.
In distributed scenarios, sharing authentication state across services via MongoDB without integrity protection can lead to tampering. An attacker who modifies a stored JSON document containing roles or permissions can elevate privileges if the application trusts the database value without re-validation. Additionally, if the ASP.NET middleware does not set secure cookie attributes (HttpOnly, Secure, SameSite) and MongoDB stores only a session identifier without binding it to IP or user-agent, session hijacking becomes feasible.
The combination also increases risk when token-based schemes (such as JWT) are stored in MongoDB for revocation tracking. Without proper TTL indexes or secure handling of refresh tokens, tokens may persist beyond their intended lifetime or be leaked through insecure logging. MiddleBrick scans detect these implementation-level risks by correlating runtime behavior with OpenAPI contracts and MongoDB interaction patterns, highlighting authentication weaknesses specific to this stack.
Mongodb-Specific Remediation in Aspnet — concrete code fixes
To mitigate Broken Authentication in ASP.NET with MongoDB, enforce strong password hashing, secure session handling, and strict validation. Use ASP.NET Identity with a custom MongoDB user store, and ensure all authentication-sensitive operations include explicit checks and secure configurations.
Secure password storage with PBKDF2
Never store passwords in plaintext or with weak hashes. Use Rfc2898DeriveBytes for PBKDF2-HMAC-SHA256 with a high iteration count and a unique salt per user.
using System;using System.Security.Cryptography;using System.Text;using MongoDB.Driver;using MongoDB.Bson;using Microsoft.AspNetCore.Identity;
public class MongoUserStore{ private readonly IMongoCollection<BsonDocument> _users;
public MongoUserStore(string connectionString, string database, string collection) { var client = new MongoClient(connectionString); var db = client.GetDatabase(database); _users = db.GetCollection<BsonDocument>(collection); }
public async Task<string> CreateUserAsync(string username, string plainPassword) { // Generate a random salt and hash the password with PBKDF2 using var deriveBytes = new Rfc2898DeriveBytes( password: plainPassword, saltSize: 16, iterations: 60000, hashAlgorithm: HashAlgorithmName.SHA256); byte[] hash = deriveBytes.GetBytes(32); // 256-bit hash byte[] salt = deriveBytes.Salt;
var user = new BsonDocument { { "username", username.ToLowerInvariant() }, // normalize to prevent enumeration { "passwordHash", Convert.ToBase64String(hash) }, { "passwordSalt", Convert.ToBase64String(salt) }, { "roles", new BsonArray() }, // assign roles later { "createdAt", DateTime.UtcNow } };
await _users.InsertOneAsync(user); return user["_id"].ToString(); }
public async Task<bool> ValidateUserAsync(string username, string plainPassword) { var user = await _users.Find(u => u["username"].AsString == username.ToLowerInvariant()).FirstOrDefaultAsync(); if (user == null) return false;
byte[] salt = Convert.FromBase64String(user["passwordSalt"].AsString); byte[] storedHash = Convert.FromBase64String(user["passwordHash"].AsString);
using var deriveBytes = new Rfc2898DeriveBytes( password: plainPassword, salt: salt, iterations: 60000, hashAlgorithm: HashAlgorithmName.SHA256); byte[] hash = deriveBytes.GetBytes(32);
return CryptographicOperations.FixedTimeEquals(storedHash, hash); }}Secure session and token handling
Bind authentication state to contextual signals and avoid long-lived tokens without rotation. Use secure, HttpOnly cookies for session identifiers and enforce SameSite and Secure flags.
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "auth_session"; options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // HTTPS only options.Cookie.SameSite = SameSiteMode.Strict; options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.SlidingExpiration = true; options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = async context => { // Optional: re-check user existence and roles in MongoDB var userStore = context.HttpContext.RequestServices .GetRequiredService<MongoUserStore>(); var username = context.Principal?.Identity?.Name; if (string.IsNullOrEmpty(username) || !await userStore.UserExistsAsync(username)) { context.RejectPrincipal(); } } }; });
builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();MongoDB-side protections
Configure MongoDB to support secure authentication workflows. Use role-based access control (RBAC) to limit what the application user can read or write. Enforce TLS for all connections and use schema validation to prevent malformed user documents.
// Example MongoDB role for the application user
// Connect with: mongosh "mongodb+srv://cluster0.example.com" --authenticationDatabase "admin"
db.createRole({
role: "app_auth_reader_writer",
privileges: [
{
resource: { db: "myappdb", collection: "users" },
actions: ["find", "update", "insert"]
},
{
resource: { db: "myappdb", collection: "sessions" },
actions: ["find", "insert", "delete"]
}
],
roles: []
});
// Enforce TLS in connection string: mongodb+srv://user:[email protected]/?tls=true&retryWrites=true&w=majority
// Schema validation example
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["username", "passwordHash", "passwordSalt"],
properties: {
username: { bsonType: "string" },
passwordHash: { bsonType: "string" },
passwordSalt: { bsonType: "string" },
roles: { bsonType: "array" },
createdAt: { bsonType: "date" }
}
}
}
});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 |