简体   繁体   中英

ASP.NET MVC: Securing actions based on parameter values

I am building a system where some users have access to certain pieces of data and not others.

How do I secure my application so that user A can get access to

/Product/1/Edit but not /Product/2/Edit

I was thinking of using an action filter for this. Is this the right way to do it?

Yes, a custom Authorize action filter is a good place to do this. Here's how you could proceed:

public class MyCustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (!(filterContext.Result is HttpUnauthorizedResult))
        {
            var currentUser = filterContext.HttpContext.User.Identity.Name;
            var currentAction = filterContext.RouteData.GetRequiredString("action");
            var id = filterContext.RouteData.Values["id"];
            if (!HasAccess(currentAction, currentUser, id))
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
    }

    private bool HasAccess(string currentAction, string currentUser, object id)
    {
        // TODO: decide whether this user is allowed to access this id on this action
        throw new NotImplementedException();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM