ASP.NET MVC and Windows Authentication with custom roles

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>

Leave a Comment