ASP.NET MVC Attribute to only let user edit his/her own content

前端 未结 4 553
深忆病人
深忆病人 2020-12-04 20:29

I have a controller method called Edit in which the user can edit data they had created like so ...

public ActionResult Edit(int id)
{
    Submi         


        
4条回答
  •  青春惊慌失措
    2020-12-04 20:35

    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
    }
    

提交回复
热议问题