Search code examples
asp.net-mvc-3role-base-authorization

How to use custom role-based authorization with Windows authentication in ASP.NET MVC3?


I'm creating an ASP.NET MVC3 intranet application with Windows authentication. I only want domain users to use this application. Once a domain user is authenticated (with Active Directory), I'm planning to create Users (with AD username), Roles & UserRoles tables in SQL Server for authorization.

So if an user is a part of a role which has some set of permissions (to access controllers/actions), I should only allow the users in that role to execute/view them.

Eg: if there is an action /Locations/Create, the roles which are allowed to perform that, can only do that.

Can somebody give me some pointers? Should I create a custom action filter, and use filter attribute to any action method that I want the filter to apply to?


Solution

  • To restrict access to an ASP.NET MVC view, you restrict access to the action method that renders the view. To accomplish this, the MVC framework provides the AuthorizeAttribute class.

    Example:

    [Authorize(Roles = "Admin, Super User")]
    public ActionResult AdministratorsOnly()
    {
     return View();
    }
    

    See here for more details.

    Note that using the [Authorize] attribute requires you to use some sort of Membership provider.