Friday 7 March 2014

How to Access User Details from Active Directory using C#

You might come across this situation of you are developing a Web Application with Windows Authentication and trying to get the User Details. It's pretty simple if your all target users are from same domain. Following code fetch the details for you.
    // Get user name
    string userName = User.Identity.Name;

    // Get domain
    using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain))
   {
        // Get User Details
        using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName))
        {
            if (user != null)
            {
                var firstName = user.GivenName;
                var emailAddress = user.EmailAddress;         
            }
        }
    }

But if you have Trusted Relationship between 2-3 different domains and your user can be anyone from any of those domains. To get the details of user, who is not on the domain where application is deployed. Following code should work for you.
   // Get user name
    string userName = User.Identity.Name;
    var domainName = username.Split('\\')[0];

    // Getting domain
    var directoryContext = new DirectoryContext(DirectoryContextType.Domain, domainName);
    Domain domain = Domain.GetDomain(directoryContext);
    using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain.Name))
   {
        // Get User Details
        using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName))
        {
            if (user != null)
            {
                var firstName = user.GivenName;           
                var emailAddress = user.EmailAddress;
            }
        }
    }

PS Hayer
Please check my other (non-CRM) blog here: Hayer's MS Dynamics CRM Blog