MVC 3 - access for specific user only

前端 未结 2 1558
陌清茗
陌清茗 2021-01-01 05:14

In my web application registered users can add new content and edit it later. I want only the content\'s author to be able to edit it. Is there any smart way of doing this o

相关标签:
2条回答
  • 2021-01-01 05:31

    I would:

    1. Save the db.aspnet_Users columm UserId (Guid) against the content record
    2. Write an extension method for your content model which verifies the current users Guid against the saved contents User Guid
    3. I would write some code that overrides this functionality for your Admin logins (I would create an Admin Role).
    0 讨论(0)
  • 2021-01-01 05:41

    Any attribute that I could use for the whole controller?

    Yes, you could extend the Authorize attribute with a custom one:

    public class AuthorizeAuthorAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized)
            {
                // the user is either not authenticated or
                // not in roles => no need to continue any further
                return false;
            }
    
            // get the currently logged on user
            var username = httpContext.User.Identity.Name;
    
            // get the id of the article that he is trying to manipulate
            // from the route data (this assumes that the id is passed as a route
            // data parameter: /foo/edit/123). If this is not the case and you 
            // are using query string parameters you could fetch the id using the Request
            var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string;
    
            // Now that we have the current user and the id of the article he
            // is trying to manipualte all that's left is go ahead and look in 
            // our database to see if this user is the owner of the article
            return IsUserOwnerOfArticle(username, id);
        }
    
        private bool IsUserOwnerOfArticle(string username, string articleId)
        {
            throw new NotImplementedException();
        }
    }
    

    and then:

    [HttpPost]
    [AuthorizeAuthor]
    public ActionResult Edit(int id)
    {
        ... perform the edit
    }
    
    0 讨论(0)
提交回复
热议问题