Как программно прочитать идентификатор арендатора или имя домена AAD, не заставляя пользователя проходить аутентификацию - PullRequest
0 голосов
/ 22 мая 2018

Мне нужно найти имя пользователя.Для этого я хочу вызвать UserPrincipal.FindByIdentity, однако мне нужно знать клиента AAD для пользователя.

Как определить арендатора?

Спасибо

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