Reputation: 443
How can I prevent the user from accessing a certail url for example /Edit/4? The id 4 does not belong to him so I want to show an unauthorized page instead.
I have a userId field in db I can check if the id in the url is ok to show.
I have tried a custom authorizeattribute but I dont know how to access the parameter sent to the 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;
}
Upvotes: 0
Views: 409
Reputation: 22619
I use to restrict access with custom Authorization filter like below
[FeatureAuthentication(AllowFeature="OverView")]
public ActionResult Index()
{
}
Then
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);
}
}
}
}
Upvotes: 1