限制对某些路由值的访问
本文关键字:访问 路由 | 更新日期: 2023-09-27 18:34:50
如何防止用户访问 certail 网址,例如/Edit/4?id 4 不属于他,所以我想显示一个未经授权的页面。
我在数据库中有一个 userId 字段,我可以检查 url 中的 id 是否可以显示。
我尝试了自定义授权属性,但我不知道如何访问发送到操作结果的参数。
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;
}
我使用自定义授权过滤器限制访问,如下所示
[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);
}
}
}
}