Home » Active Directory » AD connection and query by using PrincipalContext

AD connection and query by using PrincipalContext

There are different ways of getting data from Active Directory. One of them is that using PrincipalContext class which is a member of System.DirectoryServices namespace (Reference).

Here is a code sample to connect to Active Directory and query a user by using PrincipalContext.

using System;
using System.Web.UI;
using System.DirectoryServices.AccountManagement;

public partial class _Default : Page
    protected void Page_Load(object sender, EventArgs e)
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, System.Environment.UserDomainName); //, "DC=MyDomain,DC=com",ContextOptions.SimpleBind,"username","password");

        UserPrincipal username = UserPrincipal.FindByIdentity(ctx, System.Environment.UserName.ToUpper());

PrincipalContext authentication

PrincipalContext tries to use Kerberos authentication by default. If there are any issues with Kerberos authentication in your environment, you can use Basic Authentication by providing username and password (Reference).

Sample code for using PrincipalContext with Basic Authentication:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME", "DC=MyDomain,DC=com", ContextOptions.SimpleBind, "username","password");

Questions about Kerberos tickets? Check this post out: Kerberos ticket lifetime and renewal time

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment