[英]How to use Custom AuthorizeAttribute for controller utilizing parameter value?
I am trying to secure a controller action to prevent a user from accessing an Entity that they do not have access to. 我正在尝试保护控制器操作以防止用户访问他们无权访问的实体。 I am able to do this with the following code.
我可以使用以下代码执行此操作。
public ActionResult Entity(string entityCode)
{
if (CurrentUser.VerifyEntityPermission(entityCode))
{
//populate viewModel...
return View(viewModel);
}
return RedirectToAction("NoAccessToEntity", "Error");
}
I would like to be able to add an attribute to the controller action itself. 我希望能够为控制器操作本身添加一个属性。 In order to validate the access to the entity, I need to see what value has been passed to the controller and what entities the user has access to.
为了验证对实体的访问,我需要查看传递给控制器的值以及用户可以访问的实体。 Is this possible?
这可能吗?
[EntityAuthRequired]
public ActionResult Entity(string entityCode)
{
//populate viewModel...
return View(viewModel);
}
Something like this might help you on your way. 这样的事情可能会帮助你。 Though you may want to add some additional properties to your attribute to allow you to specify your entityCode parameter on each action, rather than hard-code it.
虽然您可能希望为属性添加一些其他属性,以允许您在每个操作上指定entityCode参数,而不是对其进行硬编码。
public class EntityAuthRequired : FilterAttribute, IAuthorizationFilter
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
//Make sure that this is not NULL before assigning value as string...
var entityCode = filterContext.RouteData.Values["entityCode"] as string;
// do your logic...
if (!allowed)
filterContext.Result = new HttpUnauthorizedResult();
}
}
Also, if the entityCode
isn't in your RouteData, you can use filterContext.RequestContext.HttpContext.Request
to look at the POST data. 此外,如果
entityCode
不在您的RouteData中,您可以使用filterContext.RequestContext.HttpContext.Request
来查看POST数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.