0

I have Windows 10/11 endpoints being a part of Azure AD domain. The local DC (hybrid mode) is disabled. I need to find out the userPrincipalName programmatically for every session/logged-in user.

Running whoami.exe /upn in the command line gives me proper UPN, like user.user@domain.com.

But the .NET code

string upn = System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName;`

fails with:

System.InvalidCastException: Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'. at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue) at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()

Is there any way to gigure out how whoami utility does the job? I cannot run any command liners from my code.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
OGP
  • 950
  • 2
  • 11
  • 26
  • The property `UserPrincipal.Current.UserPrincipalName` returns the UPN just fine. What is your program's running identity - is the line of code running under some impersonation? The exception clearly states, `GroupPrincipal` is returned and it is not casting to `UserPrincipal` type. – Anand Sowmithiran May 02 '23 at 15:03
  • No. It doesn't work as expected with pure Azure AD domain. With LDAP and Azure Hybrid it does. But I found this solution and it works: https://stackoverflow.com/questions/10946163/how-to-get-upn-for-authenticated-user-in-net-web-application-without-querying/35780463#35780463 – OGP May 02 '23 at 17:06
  • Found this solution: https://stackoverflow.com/questions/10946163/how-to-get-upn-for-authenticated-user-in-net-web-application-without-querying/35780463#35780463 The issue resolved. – OGP May 02 '23 at 17:07

0 Answers0