روشهای مقابله با مشکل امنیتی Mass Assignment در ASP.NET Core
نویسنده: سالار ربال
تاریخ: ۱۳۹۷/۱۲/۲۹ ۱۸:۴۲
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
This was a very quick run down of some of the options available to you to prevent mass assignment. Which approach you take is up to you, though I would definitely suggest using one of the latter 2-model approaches. There are other options too, such as doing explicit binding via TryUpdateModelAsync<> but the options I've shown represent some of the most common approaches. Whatever you do, don't just blindly bind your view models if you have properties that should not be edited by a user, or you could be in for a nasty surprise.
And whatever you do, don't bind directly to your EntityFramework models. Pretty please.
public class UserModel
{
[MaxLength(200)]
[Display(Name = "Full name")]
[Required]
public string Name { get; set; }
}
public class UserModalViewModel
{
public UserModel Model { get; set; }
public bool IsAdmin { get; set; }
public IReadonlyList<lookupitem> Roles { get; set; }
} [HttpGet]
public async Task<IActionResult> Edit(int id)
{
var user = await _service.FindAsync(id); //return Maybe<UserModel>
if (!user.HasValue)
{
return NotFound();
}
// prepare model
var model = new UserModalViewModel
{
Model = user.Value,
IsAdmin = true,
Roles = await _lookupService.ReadRolesAsync()
};
return View(model);
} [HttPost]
public async Task<IActionResult> Edit([Bind(Prefix = "Model")] UserModel model)
{
//todo: check ModelState and save model
await _service.EditAsync(model);
}