I need to look up the user principal name. For this purpose, I want to call UserPrincipal.FindByIdentity however I need to know the AAD tenant for the user.
How do I determine the tenant?
Thanks
public string GetUpnForLoggedOnUser()
{
// Tried an approach via
// var ds = System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName;
// but throws invalid cast on the AAD joined client.
var windowsIdentity = WindowsIdentity.GetCurrent();
// WindowsIdentity.Name is NOT an UPN, bad code, bad code!
return windowsIdentity.Name;
/*
* Code below works on my desktop, but on AAD joined machine throws
* System.DirectoryServices.AccountManagement.PrincipalServerDownException:
* The server could not be contacted. ---> System.DirectoryServices.Protocols.LdapException: The LDAP server is unavailable.
* Which is readonable since we need to constuct the PrincipalContext with a domain name (which we don't have)
*/
using (var principalContext = new PrincipalContext(ContextType.Domain))
{
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, windowsIdentity.Name);
Console.WriteLine($"Context Type: {userPrincipal.Context.ContextType}");
Console.WriteLine($"Context Name: {userPrincipal.Context.Name}");
return userPrincipal.UserPrincipalName;
}
}