0

如何防止用户访问 certail url,例如 /Edit/4?id 4 不属于他,所以我想显示一个未经授权的页面。

我在 db 中有一个 userId 字段,我可以检查 url 中的 id 是否可以显示。

我尝试了自定义授权属性,但我不知道如何访问发送到 actionresult 的参数。

public class EditOwnAttribute : AuthorizeAttribute
{
    // Custom property
    public string Level { get; set; }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }




        return false;
    }
4

1 回答 1

1

我使用自定义授权过滤器来限制访问,如下所示

    [FeatureAuthentication(AllowFeature="OverView")]
    public ActionResult Index()
    {
    }

然后

public class FeatureAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
    public FeatureConst AllowFeature { get; set; }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        //var featureConst = (FeatureConst)filterContext.RouteData.Values["AllowFeature"];

        var filterAttribute = filterContext.ActionDescriptor.GetFilterAttributes(true)
                                .Where(a => a.GetType() == typeof(FeatureAuthenticationAttribute));
        if (filterAttribute != null)
        {
            foreach (FeatureAuthenticationAttribute attr in filterAttribute)
            {
                AllowFeature = attr.AllowFeature;
            }

            User currentLoggedInUser = (User)filterContext.HttpContext.Session["CurrentUser"];
            bool allowed = ACLAccessHelper.IsAccessible(AllowFeature.ToString(), currentLoggedInUser);
            // do your logic...
            if (!allowed)
            {
                string unAuthorizedUrl = new UrlHelper(filterContext.RequestContext).RouteUrl(new { controller = "home", action = "UnAuthorized" });
                filterContext.HttpContext.Response.Redirect(unAuthorizedUrl);
            }
        }
    }
}
于 2013-10-11T13:28:45.777 回答