2

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?

1 Answer 1

6

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.