0

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;
        }
    }
Martin K
  • 183
  • 9
  • How about `Environment.UserName` or `Environment.UserDomainName`? What type of project is this? – Camilo Terevinto May 22 '18 at 00:45
  • 2
    Azure AD does not support LDAP. In fact Azure AD is pretty different from AD though the naming is confusing. You should be able to get the info from the `ClaimsPrincipal.Current` if you have implemented OpenId Connect/WS-Fed authentication. – juunas May 22 '18 at 05:42
  • @CamiloTerevinto UserDomainName is 'AzureAD' for my Azure AD joined machine. So that approach only works for traditional AD – Martin K May 22 '18 at 15:55
  • @juunas so you're saying even if I used a different PrincipalContext constructor, it would not work because FindByIdentity relies on LDAP to do its work? – Martin K May 22 '18 at 16:59
  • 1
    Yeah, that's right. – juunas May 22 '18 at 17:12

0 Answers0