【发布时间】:2020-07-21 11:29:51
【问题描述】:
现在我在下面的代码中检查用户的对象所有权(我注释了代码的重要部分)。而且我对应用程序中的每个模型和每个控制器方法都这样做,这完全违反了DRY 原则。也许你有一些想法可以避免重复?
此外,我不确定它是否安全,并且用户将无法通过一些技巧访问其他人的数据。我正在做的事情安全吗?
这是关于个人数据安全的一个非常重要的话题,我相信应该有某种文档。不幸的是,我没有找到任何文档,如果我没有很好地搜索,我会很高兴看到任何链接。
TasksController.cs
public async Task<IActionResult> Index()
{
// here I form a selection from objects belonging to the current user
var Tasks = _context.Tasks.Where(t => t.UserId.Equals(User.Identity.GetUserId()));
return View(await applicationDbContext.ToListAsync());
}
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var task = await _context.Tasks.FindAsync(id);
// here I check if the requested object belongs to the current user
if (task == null | task.UserId != User.Identity.GetUserId())
{
return NotFound();
}
return View(task);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,TaskTypeId,Status,UserId")] Task task)
{
if (ModelState.IsValid)
{
// here i am assigning object's UserId to id of current user
task.UserId = User.Identity.GetUserId();
_context.Add(task);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(task);
}
【问题讨论】: