Accessing Active Directory from ASP.Net MVC using C#

Russ Clark picture Russ Clark · Jun 2, 2010 · Viewed 36.4k times · Source

I need to access Active Directory to get information about groups that customers belong to. The project I have is an ASP.Net MVC application using C#. I've never programmed against Active Directory before, and need some advice on what the best way to get started is, what security model to use to access the information, and maybe point me to some good tutorials.

Answer

tvanfosson picture tvanfosson · Jun 2, 2010

Since you're using MVC, you have access to the new System.DirectoryServices.AccountManagement namespace in .NET 3.5. These classes should be preferred over the older classes in DirectoryServices itself as they are much simpler to use. There are a couple of gotchas that haven't been solved in 3.5 (1500 member limit when querying groups, for instance), but I'm assured that these have been fixed in .NET 4.0. For most tasks, the new classes work very well.

 using (var context = new PrincipalContext( ContextType.Domain )) 
 {
      using (var user = UserPrincipal.FindByIdentity( context, "username" ))
      {
          var groups = user.GetAuthorizationGroups();
          ...
      }
 }