Permission based authorization .net identity
.net, asp.net-identity, asp.net-mvc, user-permissions
Solution
You can implement your custom `AuthorizationAttribute` where you will specify your parameters and can get a `blogId` from request
public class AuthorizeEntryPermission : AuthorizeAttribute
{
public string Permission { get; set; }
public AuthorizeEntryPermission(){
}
public AuthorizeEntryPermission(string Permission)
{
this.Permission = Permission;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var id = context.Request.RequestContext.RouteData.Values["Id"];
//check your permissions
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (AuthorizeCore(filterContext.HttpContext))
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
}
else
{
//handle no permission
}
}
private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
{
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
}
Then use it like this:
[AuthorizeEntryPermission(Permission = "Edit")]
public ActionResult Edit(int? Id){
//edit action
}
Problem
I am new to .NET, MVC & Identity Framework. I noticed the identity framework allows for securing individual controller actions via annotations. ``` [Authorize] public ActionResult Edit(int? Id){ //edit action } ``` I would like to secure certain actions based on user permissions. Example : A blog application where only the user who created a blog post can edit. With this in mind, is it possible to perform either option below? If so, are there resources and examples on how to best achieve? ``` [Authorize(Entity = "Entry", Permission = "Edit", Id = Id)] public ActionResult Edit(int? Id){ //edit action } ``` or ``` [BlogEntryPermission(Permission = "Edit", Id = Id)] public ActionResult Edit(int? Id){ //edit action } ``` Where blog `Id` is captured from the request. Any information or direction on permission based authentication would be most appreciated. Thanks in advance for your help.