user1404577
user1404577

Reputation:

How to pass a UserPrincipal with PrincipalContext inside ASP.NET MVC

I have the following code to connect to our AD :-

List<DomainContext> results = new List<DomainContext>();
string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];

using (var context = new PrincipalContext(ContextType.Domain, ADServerName))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{

The above worked on our Dev machine as the AD and the asp.net mvc were on the same machine. currently I need to connect to our staging AD which is on different machine. so I need to pass the AD service account (username & password) to the PrincipalContext. Can anyone advice? I read online that I need to use UserPrincipal as follow:-

public UserPrincipal(
    PrincipalContext context,
    string samAccountName,
    string password,
    bool enabled
)

but I am not sure how I can modify my code accordingly ?

Thanks

EDIT I tried this to display only user that have brancjA or brachB inside their distinguished accounts:-

public List<DomainContext> GetADUsers(string term=null)
        {
            string[] types = new string[] { "BranchA", "BranchB" };
            List<DomainContext> results = new List<DomainContext>();
            string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
            using (var context = new PrincipalContext(ContextType.Domain, ADServerName, "username", "password"))
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {
                var searchResults = searcher.FindAll();



                foreach (Principal p in searchResults)
                {
                   if ((term == null || p.SamAccountName.ToString().ToUpper().StartsWith(term.ToUpper())) && (types.Contains(p.DistinguishedName)))

but the result was that no users were returned. can you advice please ?

Upvotes: 1

Views: 14384

Answers (1)

marc_s
marc_s

Reputation: 754230

Are you talking about creating the PrincipalContext and supplying specific credentials (username + password) in doing so?

Check out the fabolous MSDN documentation on PrincipalContext - freely available to anyone - use it!

As you can see, the PrincipalContext has several overloaded constructors to allow various scenarios:

enter image description here

You'll probably want to use this constructor here:

public PrincipalContext(
    ContextType contextType,
    string name,
    string userName,
    string password
)

This allows you to pass in a user name and a password to use for all your AD operations under this context.

Update: the follow-up question about returning only the "normal" users (and ignoring the "service accounts") - when you use a PrincipalSearcher, you can define a "query-by-example" principal to do your searching:

// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // define a "query-by-example" principal - here, we search for a UserPrincipal 
   // and with the first name (GivenName) of "Bruce" and a last name (Surname) of "Miller"
   UserPrincipal qbeUser = new UserPrincipal(ctx);
   qbeUser.GivenName = "Bruce";
   qbeUser.Surname = "Miller";

   // create your principal searcher passing in the QBE principal    
   PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

   // find all matches
   foreach(var found in srch.FindAll())
   {
       // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
   }
}

Of course, depending on your need, you might want to specify other properties on that "query-by-example" user principal you create:

  • DisplayName (typically: first name + space + last name)
  • SAM Account Name - your Windows/AD account name
  • User Principal Name - your "[email protected]" style name

You can specify any of the properties on the UserPrincipal and use those as "query-by-example" for your PrincipalSearcher. So really - you only need to find the proper way to express the criteria which distinguishes the "normal" users from the "service accounts" in your PrincipalSearcher and you should be able to do this just fine

Update #2: what I meant was something like this:

// create list to hold results
List<Principal> allNormalUsers = new List<Principal>();            

// first, search OU=BranchA
using (var context = new PrincipalContext(ContextType.Domain, ADServerName, "OU=BranchA,OU=Users", "username", "password"))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
    allNormalUsers.AddRange(searcher.FindAll());
}

// after that, search OU=BranchB
using (var context = new PrincipalContext(ContextType.Domain, ADServerName, "OU=BranchB,OU=Users", "username", "password"))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
    allNormalUsers.AddRange(searcher.FindAll());
}

// and now your "allNormalUsers" should contain all "normal" users from OU=BranchA 
// and from OU=BranchB

Upvotes: 2

Related Questions