Custom authorization with capabilities table in MVC 5

176 Views Asked by At

I wanna know if it is possible to create a custom authentication - authorization, by extending the existing authentication with MVC 5 in C#. Basically what I want is to be able to allow access to methods or entire controllers by hinting the capabilities like you normally do with roles:

public class User : Controller
{
    // POST: Users/Create
    [Authorize(Capabilities= "CreateUsers")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(FormCollection form)
    {
    }
}

I don't wanna use Roles ([Authorize(Roles = "Administrator")]), because my users will have Capabilities. I already have custom tables in my database for Users, Capabilities and CapabilityUser.

1

There are 1 best solutions below

0
On
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    public string Capabilities { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Check capablities here
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        // Decide what to do with unauthorized requests
    }
}

and then use it as

[MyAuthorize(Capabilities= "CreateUsers")]