ASP.NET MVC and Windows Authentication with custom roles

Solution 1:

Just create a new principal and assign it to the user and thread in Global.asax (or use an action filter).

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;
  }
}

If a user doesn't have any role that matches, they can be barred from the app using the web.config authoirzation element:

<authorization>
  <allow roles="blah,whatever"/>
  <deny users="*"/>               
</authorization>

Solution 2:

Just to add to the above answer, Hope this save some fokes some time.

I have a intranet MVC 5 site with VS 2015.

The code did not work for me until the top line was updated with HttpContext.Current.User. The site was giving me null reference to the HttpContext.Current.User if the user wasn't already created in the Database. By adding .User to the first line, it bypassed that code on first load and worked.

if (HttpContext.Current.User != null)
        {


            String[] roles = GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name);

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

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