[英]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 如何保护我的应用程序,以便用户A可以访问
/Product/1/Edit
but not /Product/2/Edit
/Product/1/Edit
但不是/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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.