ASP.NET MVC Attribute to only let user edit his/her own content
.net, asp.net-mvc, authentication, c#, security
Solution
Yes, you could achieve that through a custom Authorize attribute:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
return false;
}
var rd = httpContext.Request.RequestContext.RouteData;
var id = rd.Values["id"];
var userName = httpContext.User.Identity.Name;
Submission submission = unit.SubmissionRepository.GetByID(id);
User user = unit.UserRepository.GetByUsername(userName);
return submission.UserID == user.UserID;
}
}
and then:
[MyAuthorize]
public ActionResult Edit(int id)
{
// Carry out method
}
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:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
return false;
}
var rd = httpContext.Request.RequestContext.RouteData;
var id = rd.Values["id"];
var userName = httpContext.User.Identity.Name;
Submission submission = unit.SubmissionRepository.GetByID(id);
User user = unit.UserRepository.GetByUsername(userName);
rd.Values["model"] = submission;
return submission.UserID == user.UserID;
}
}
and then:
[MyAuthorize]
public ActionResult Edit(Submission model)
{
// Carry out method
}
Problem
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.