如何阻止用户访问certail url,例如/ Edit / 4? id 4不属于他,所以我想要显示未经授权的页面。
我在db中有一个userId字段我可以检查url中的id是否可以显示。
我尝试过自定义authorizeattribute,但我不知道如何访问发送给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;
}
答案 0 :(得分: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);
}
}
}
}