Skip to content

Instantly share code, notes, and snippets.

@RobertBonham
Created October 17, 2013 01:14
Show Gist options
  • Save RobertBonham/7017748 to your computer and use it in GitHub Desktop.
Save RobertBonham/7017748 to your computer and use it in GitHub Desktop.
Asp.Net MVC 4 Base Controller to expose AD User information
public class AdLookup
{
public static DomainContext GetUserDetails()
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
IPrincipal principal = HttpContext.Current.User;
WindowsIdentity identity = ((WindowsIdentity)principal.Identity);
UserPrincipal user = UserPrincipal.FindByIdentity(pc, identity.Name);
if (principal != null)
{
return new DomainContext()
{
userGuid = user.Guid,
DisplayName = user.DisplayName,
GivenName = user.GivenName,
EmailAddress = user.EmailAddress,
Groups = user.GetGroups().OrderBy(p=>p.Name).Select(p=>p.Name).ToList()
};
}
}
return null;
}
}
public class BaseController : Controller
{
//Makes userContext avaiable in any controller inheriting from BaseController
public DomainContext userContext { get; set; }
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
userContext = AdLookup.GetUserDetails();
ViewData["BaseController_DomainContext"] = userContext;
}
}
public class DomainContext
{
//Populate with any needed properties from Prinipal
public Guid? userGuid { get; set; }
public string DisplayName { get; set; }
public string GivenName { get; set; }
public string EmailAddress { get; set; }
public List<string> Groups { get; set; }
}
@using MvcApplication2.Controllers
@{
ViewBag.Title = "Index";
DomainContext domainContext = (DomainContext)ViewData["BaseController_DomainContext"];
}
<h2>@domainContext.DisplayName</h2>
<hr/>
Welcome: @domainContext.GivenName <br/>
eMail: @domainContext.EmailAddress <br/>
Guid: @domainContext.userGuid
<h2>Groups:</h2>
@foreach (string name in domainContext.Groups)
{
<li>@name</li>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment