What is over-posting (mass assignment), and how do you prevent it?
Quick Answer
Over-posting is when a user submits form fields your form didn't render — like IsAdmin=true — and the model binder happily sets them on your entity. Prevent it by binding to a purpose-built view model / DTO that only has the fields the user is allowed to change, then map those onto the entity.
Over-posting is when the model binder sets a property that your form never showed. If my POST action binds directly to the EF User entity and that entity has an IsAdmin flag, an attacker just adds IsAdmin=true to the form data and the binder sets it. The clean fix is to never bind to the entity — bind to a view model that only contains the fields the user should be able to edit, then load the actual entity and copy those specific fields onto it. The [Bind] attribute is a weaker fallback because you forget to update it.
- The bug:
[HttpPost] public IActionResult Edit(User user)binding straight to the EF entity — an attacker addsRole=Adminto the POST and it sticks. - Best fix:
Edit(UserEditViewModel vm)with onlyName,Email; load the realUser, copy the allowed fields, save. - Weaker mitigations:
[Bind(Include = "Name,Email")]or[BindNever]on sensitive properties — easy to forget when a new property is added. - Same principle applies to Web API request DTOs.