What is JSON injection?
JSON injection occurs when an attacker manipulates the structure of a JSON payload to insert unexpected keys, values, or scripts.
Attackers exploit
Extra fields (e.g., isAdmin: true ).
Script injection inside JSON strings (leading to XSS if improperly handled).
Malformed JSON to crash parsers or bypass validations.
Example Attack Payload
{
"username": "attacker",
"email": "[email protected]",
"isAdmin": true, // Sensitive field injection
"__proto__": { "polluted": "yes" } // Prototype pollution attack
}
If your API model-binds this blindly into your entity, attackers can escalate privileges or poison objects.
Risks of Malformed JSON
Denial of Service (DoS): Sending enormous JSON payloads.
Deserialization flaws: Exploiting weak parsers (e.g., type confusion).
Validation bypass: Sending unexpected JSON structures.
How to Protect in ASP.NET Core?
1. Use DTOs Instead of Entities
Never accept raw JSON into entity models. Define Data Transfer Objects (DTOs) with strict fields.
public class RegisterDto
{
[Required, StringLength(50)]
public string Username { get; set; }
[Required, EmailAddress]
public string Email { get; set; }
[Required, StringLength(100)]
public string Password { get; set; }
}
Controller
[HttpPost("register")]
public IActionResult Register([FromBody] RegisterDto dto)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
// Safe mapping
var user = new User
{
Username = dto.Username,
Email = dto.Email,
IsAdmin = false // Explicitly controlled
};
return Ok(user);
}
Prevents attackers from injecting extra JSON properties, such as isAdmin.
2. Reject Unknown Properties
By default, System. Text.Json ignores unknown fields. Force it to fail on unknown JSON properties.
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Disallow;
options.JsonSerializerOptions.AllowTrailingCommas = false;
options.JsonSerializerOptions.UnknownTypeHandling = System.Text.Json.Serialization.JsonUnknownTypeHandling.Fail;
options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
});
Or, in Newtonsoft.Json.
Join the conversation! Your thoughts help the community grow.