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 t开发者_运维百科hinking 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();
}
}
精彩评论