Tuesday, March 06, 2012

Finding a UserPrincipal for an email address

I wanted to let users log in to our application using their Windows user name or their email address. In order to achieve this aim, I needed to get hold of a UserPrincipal from the user’s email address so I could then test the password they entered was correct. It took quite a lot of searching to find the relevant code, so I thought I’d post the pertinent part here.

      PrincipalContext context = new PrincipalContext(
        ContextType.Domain, Environment.UserDomainName);
      
      UserPrincipal user = new UserPrincipal(context);
      user.EmailAddress = "test@test.com";

      // create a principal searcher for running a search operation
      PrincipalSearcher pS = new PrincipalSearcher(user);

      // run the query
      PrincipalSearchResult<Principal> results = pS.FindAll();

      foreach (Principal result in results)
      {
        // do something useful...
      }

4 comments:

Anonymous said...

Thanks!

Anonymous said...

Saved me time. Thank you.

jtpatil said...

This saved me a lot of time. Thanks!

D. Rowe said...

This was really bugging me yesterday. Thank you so much!