How to get UPN for authenticated user in .NET web application without querying Active Directory

(This question is similar to Get UPN or email for a registered user in a .NET web application , but not quite.)

In a .NET web application (C #) using Windows authentication, I would like to find the UPN of the registered user.

I know how to do this by querying Active Directory: get "DOMAINNAME \ username" from HttpContext.Current.User.Identity as WindowsIdentity ; find DOMAINNAME under ldap://RootDSE and find its dnsRoot ; request (&(objectCategory=person)(objectClass=user)(sAMAccountName=...userName...)) under ldap://...dnsRoot... ; get this userPrincipalName entry. (For more details see At https://stackoverflow.com/a/266182/ ).

My question is: Is it possible to find UPN without calling Active Directory? Given that Microsoft is focused on using UPN everywhere, isn’t the UPN already stored somewhere in the token that is created when the user authenticates on the web server?

(Auxiliary observation: if I run whoami /upn on Windows 7, then Wireshark does not show any Active Directory connections.)

(If that matters: note that our web application does not use impersonation , that is, our web application does not start under the user ID.)

+4
source share
2 answers

Try System.DirectoryServices.AccountManagement.UserPrincipal.Current , which has the UserPrincipalName property. Of course, this will require the application to run under Windows authentication.

Edit Fur, it looks like this API is still doing a directory search.

+4
source

I was having problems querying Active Directory when using System.DirectoryServices.AccountManagement.UserPrincipal.Current , so I resorted to using GetUserNameEx using the NameUserPrincipal format.

This function receives information about the current user, so it requires that you impersonate yourself if you have not already done so. In C #, this can be done by importing a function:

 public enum EXTENDED_NAME_FORMAT { NameUnknown = 0, NameFullyQualifiedDN = 1, NameSamCompatible = 2, NameDisplay = 3, NameUniqueId = 6, NameCanonical = 7, NameUserPrincipal = 8, NameCanonicalEx = 9, NameServicePrincipal = 10, NameDnsDomain = 12 } [DllImport("secur32.dll", CharSet = CharSet.Auto)] public static extern int GetUserNameEx(int nameFormat, StringBuilder userName, ref int userNameSize); 

Then call it like this:

 string upn = null; StringBuilder userName = new StringBuilder(1024); int userNameSize = userName.Capacity; if (GetUserNameEx((int)EXTENDED_NAME_FORMAT.NameUserPrincipal, userName, ref userNameSize) != 0) { upn = userName.ToString(); } 
+2
source

All Articles