I have a controller method called Edit in which the user can edit data they had created like so …
public ActionResult Edit(int id)
{
Submission submission = unit.SubmissionRepository.GetByID(id);
User user = unit.UserRepository.GetByUsername(User.Identity.Name);
//Make sure the submission belongs to the user
if (submission.UserID != user.UserID)
{
throw new SecurityException("Unauthorized access!");
}
//Carry out method
}
This method works fine however it is a little messy to put in every controller Edit method. Each table always has a UserID so I was wondering if there was an easier way to automate this via an [Authorize] Attribute or some other mechanism to make the code cleaner.
Yes, you could achieve that through a custom Authorize attribute:
and then:
and let’s suppose that you need to feed this submission instance that we fetched into the custom attribute as action parameter to avoid hitting the database once again you could do the following:
and then: