views:

1109

answers:

2

I'm not a .NET developer, and I have a feeling this would be trivial for someone who is:

I have a C# web application that makes user of the user credentials of the logged in user. Currently it uses the SID which comes from

System.Security.Principal.WindowsIdentity.GetCurrent().User.Value

I need to get either the users UPN login or email address (as defined in active directory) instead of the SID. GetCurrent() returns an object of type WindowsIdentity; looking in the details for WindowsIdentity Members:

MSDN: WindowsIdentity Members

I can't see anything that looks like it would give me either the UPN or email in there. How can I pull up that information to use, either by feeding the SID into some other function or calling something different in the first place.

+1  A: 

Try:

System.Security.Principal.WindowsIdentity.GetCurrent().Name
Jimmy Chandra
The documentation says "Gets the user's Windows logon name." - will this return the NT-style name or the UPN style name? I know Microsoft said many years ago that UPN woudl be the new way to identify users, but in my experience almost everything works off NT Style credentials - and users can login to this site with either UPN or NT Style logoins so I can't rely on it using the same form the user did.
DrStalker
Just did a quick test and System.Security.Principal.WindowsIdentity.GetCurrent().Name is returning DOMAIN\username
DrStalker
from that, you can feed it into DirectorySearcher object to get more details on that particular user. For DirectorySearcher, see http://www.dotnetactivedirectory.com/Understanding_LDAP_Active_Directory_User_Object_Properties.html, http://blog.lozanotek.com/articles/149.aspx and http://codebetter.com/blogs/peter.van.ooijen/archive/2006/12/12/Getting-information-out-of-active-directory_3A00_-DirectorySearcher_2C00_-Properties-and-DirectoryEntry.aspx.
Jimmy Chandra
+1  A: 

To query active directory using a directory searcher you need to do something like this (totally untested code):

    string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    string ldapPath = "LDAP://domain.company.com";

    public string GetEmail(string userName, string ldapPath)
    {
        using (DirectoryEntry root = new DirectoryEntry(ldapPath))
        {
            DirectorySearcher searcher = new DirectorySearcher(root);
            searcher.Filter = string.Format(@"(&(sAMAccountName={0}))", userName);
            searcher.PropertiesToLoad = "mail";

            SearchResult result = searcher.FindOne();

            if (result != null)
            {
                PropertyValueCollection property = result.Properties["mail"];
                return (string)property.Value;
            }
            else
            { 
                // something bad happened
            }
        }
    }
Alex Peck