MVC 4 Intranet Authentication with Custom Roles

SQLGrinder picture SQLGrinder · Jan 22, 2013 · Viewed 12.8k times · Source

I have spent some time searching and found a lot of confusing answers, so I will post here for clarification.

I am using MVC4 VS2012 created an Intranet site using domain authentication. Everything works. However, to manage the users that have access to different areas of this webapp I prefer not to use AD groups that I cannot manage and nor can the users of the webapp.

Is there an alternative? I assume this would involve associating/storing domain names belonging to custom roles and using the Authorize attribute to control access.

[Authorize(Roles = "Managers")]

Can anyone suggest the best pattern for this or point me in the right direction?

I see a similar solution link, but I am still not sure how to use this against a stored list of roles and validate the user against those roles. Can anyone elaborate if this solution would work?

        protected void Application_AuthenticateRequest(object sender, EventArgs args)
    {
        if (HttpContext.Current != null)
        {
            String[] roles = GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name);

            GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);

            Thread.CurrentPrincipal = HttpContext.Current.User = principal;
        }
    }

Answer

Pablo Claus picture Pablo Claus · Jan 22, 2013

I'm using this configuration with SQL Server and MVC3.

Web.config:

<system.web>
<roleManager enabled="true" defaultProvider="SqlRoleManager">
  <providers>
    <clear />
    <add name="SqlRoleManager" type="System.Web.Security.SqlRoleProvider"   connectionStringName="SqlRoleManagerConnection" applicationName="YourAppName" />
  </providers>
</roleManager>

....

<authentication mode="Windows" />

....

<connectionStrings>

<add name="SqlRoleManagerConnection" connectionString="Data Source=YourDBServer;Initial Catalog=AppServices;Integrated Security=True;" providerName=".NET Framework Data Provider for OLE DB" />
</connectionStrings>

To inicialize roles:

Global.asax.cs

using System.Web.Security;

////
protected void Application_Start()
{

   //You could run this code one time and then manage the rest in your application.
   // For example:

   // Roles.CreateRole("Administrator");    
   // Roles.AddUserToRole("YourDomain\\AdminUser", "Administrator");


   Roles.CreateRole("CustomRole");   

   Roles.AddUserToRole("YourDomain\\DomainUser", "CustomRole");

 }

In your Controller

[Authorize(Roles ="CustomRole")]
public class HomeController : Controller
 {

To manage users

 public class Usuario
{
    public string UserName { get; set; }
    public string RoleName { get; set; }
    public string Name { get; set; }
    public const string Domain = "YourDomain\\";


    public void Delete()
    {
        Roles.RemoveUserFromRole(this.UserName, this.RoleName);
    }

    public void Save()
    {
        if (Roles.IsUserInRole(Usuario.Domain + this.UserName, this.RoleName) == false)
        {
            Roles.AddUserToRole(Usuario.Domain + this.UserName, this.RoleName);
        }
    }
}

Users Class

public class Usuarios : List<Usuario>
{

    public void GetUsuarios() //Get application's users
    {

        if (Roles.RoleExists("CustomRole"))
        {
            foreach (string _usuario in Roles.GetUsersInRole("CustomRole"))
            {
                var usuario = new Usuario();
                usuario.UserName = _usuario;
                usuario.RoleName = "CustomRole";
                this.Add(usuario);
            }
        }
  //

  public void GetUsuariosRed() //Get Network Users (AD)
    {
        var domainContext = new PrincipalContext(ContextType.Domain);
        var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, "Domain Users");

        foreach (var item in groupPrincipal.Members)
        {
            var usuario = new Usuario();
            usuario.UserName = item.SamAccountName;
            usuario.Name = item.Name;
            this.Add(usuario);
        }

    }

You can create an "Admin" controller like this, to manage the users:

[Authorize(Roles = "AdminCustomRole")]
public class AdminController : Controller
{

//

public ActionResult Index()
    {

        var Usuarios = new Usuarios();
        Usuarios.GetUsuarios();
        return View(Usuarios);

    }

[HttpGet]
public ActionResult CreateUser()
    {

        var Usuarios = new Usuarios();
        Usuarios.GetUsuariosRed();

       return View(Usuarios);

    }

//

In my application, custom roles are fixed.