Search code examples
c#active-directorywindows-authentication

Windows Authentication User.Identity.Name to email address


I have already tried to use How to obtain email address with window authentication, but a question remains:

I know how to ask for email address for John Smith, but what I get as authentication name is like INTRA\\JohnSmith3 or DEP21\\JohnSmith

How can I map INTRA\\JohnSmith3 or DEP21\\JohnSmith to the correct John Smith in AD?


Solution

  • What you get from Windows Authentication is the SAM Account Name. You need to look this up in Active Directory.

    You can query Active Directory for users like this:

    (&(objectCategory=person)(objectClass=user)(sAMAccountName=JohnSmith3))
    

    In code:

    string filter = "(&(objectCategory=person)"
         + "(objectClass=user)"
         + "(sAMAccountName=" + samAccountName + "))";
    DirectorySearcher search = new DirectorySearcher(myLdapConnection);
    search.Filter = filter;
    SearchResult result = search.FindOne();
    DirectoryEntry de = result.GetDirectoryEntry();