0

On my website, I have different pages with different levels of access permissions. Usually, I use something along:

if(!user.IsAdministrator)
    return RedirectToAction("AccessDenied", "Security");

But I realized this was tieing me to the security levels that I'd prebuilt; what I in fact want is a fully customizable access scheme.

One solution I thought about was to set some attributes in the actions I wanted to give restricted access, then retrieve where were they placed. I'm somewhat unexperienced with Attributes (custom ones, at least), and although I know how to list all the actions being marked, I'm still struggling to conceive a way to check for the right access permission and denying the access.

Any light on the subject? I'm also interested to know if there are any standard practices for dealing with this issue.

1 Answers1

1

Typically in ASP.NET MVC Authorize attribute is what can be used for such purpose.

You can derive from it and override AuthorizeCore method to satisfy your needs. Then you can mark MVC actions or whole MVC controllers with this attribute. Or what is even better you can configure it as a global filter, so it will automatically be automatically enabled for all controllers. Then actions you don't want to be secured can be marked with AllowAnonymous attribute: http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        if (filters != null)
        {
            filters.Add(new CustomAuthorizeAttribute());
        }
    }


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //your code here
    }

Here is SO post that already discusses the attribute ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

You can find more articles on this topic on the internet.

Community
  • 1
  • 1
Ihor Deyneka
  • 1,326
  • 1
  • 19
  • 37