Get UPN or email for logged in user in a .NET web application

后端 未结 3 450
误落风尘
误落风尘 2020-12-10 01:16

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

相关标签:
3条回答
  • 2020-12-10 01:33

    Try:

    System.Security.Principal.WindowsIdentity.GetCurrent().Name
    
    0 讨论(0)
  • 2020-12-10 01:49

    Meanwhile (.NET 3.5) this is a one-liner:

    System.DirectoryServices.AccountManagement.UserPrincipal.Current.EmailAddress
    

    for the email, or

    System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName
    

    for the UPN.

    0 讨论(0)
  • 2020-12-10 01:56

    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
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题