DrStalker
DrStalker

Reputation: 9601

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

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.

Upvotes: 28

Views: 32891

Answers (3)

Kiki
Kiki

Reputation: 496

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.

Upvotes: 48

Alex Peck
Alex Peck

Reputation: 4711

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
            }
        }
    }

Upvotes: 3

Jimmy Chandra
Jimmy Chandra

Reputation: 6580

Try:

System.Security.Principal.WindowsIdentity.GetCurrent().Name

Upvotes: 2

Related Questions