MVC 3 - access for specific user only

2019-02-07 10:39发布

问题:

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 other than manually writing code in all the action methods that checks if the logged user is the same as the author? Any attribute that I could use for the whole controller?

回答1:

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
}


回答2:

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).