Олицетворение и DirectoryEntry - PullRequest
7 голосов
/ 22 января 2012

Я успешно олицетворяю учетную запись пользователя, но не могу использовать олицетворенную учетную запись для привязки к AD и снятия DirectoryEntry.

Приведенный ниже код выводит:

  • До олицетворения я: DOMAIN \ user
  • После олицетворения я: DOMAIN \ admin
  • Ошибка:C: \ Users \ user \ ADSI_Impersonation \ bin \ Debug \ ADSI_Impersonation.exe имя samaccount:

Моя проблема похожа на:

Как использовать пространство имен System.DirectoryServicesв ASP.NET

я получаю первичный токен.Я понимаю, что мне нужно использовать делегирование для использования олицетворенного токена на удаленном компьютере.Я подтвердил, что для учетной записи не установлен флажок «Учетная запись конфиденциальна и не может быть делегирована».Я также подтвердил, что локальная групповая политика и групповые политики домена не препятствуют делегированию:

Конфигурация компьютера \ Конфигурация Windows \ Параметры безопасности \ Локальные политики \ Назначение прав пользователя \

Чего мне не хватает?

Спасибо!

using System;
using System.DirectoryServices;
using System.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;

namespace ADSI_Impersonation
{
    class Program
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);

        static void Main(string[] args)
        {
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_INTERACTIVE = 2;

            string userName = "admin@domain.com";
            string password = "password";

            Console.WriteLine("Before impersonation I am: " + WindowsIdentity.GetCurrent().Name);

            SafeTokenHandle safeTokenHandle;

            try
            {
                bool returnValue = LogonUser(userName, null, password,
                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                    out safeTokenHandle);

                if (returnValue)
                {
                    WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                    WindowsImpersonationContext impersonatedUser = newId.Impersonate();
                }
                else
                {
                    Console.WriteLine("Unable to create impersonatedUser.");
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Authentication error.\r\n" + e.Message);
            }

            Console.WriteLine("After impersonation I am: " + WindowsIdentity.GetCurrent().Name);

            string OU = "LDAP://dc=domain,dc=com";
            DirectoryEntry entry = new DirectoryEntry(OU);
            entry.AuthenticationType = AuthenticationTypes.Secure;

            DirectorySearcher mySearcher = new DirectorySearcher();
            mySearcher.SearchRoot = entry;
            mySearcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
            mySearcher.PropertiesToLoad.Add("cn");
            mySearcher.PropertiesToLoad.Add("samaccountname");

            string cn = "fistname mi. lastname";
            string samaccountname = "";

            try
            {
                // Create the LDAP query and send the request
                mySearcher.Filter = "(cn=" + cn + ")";

                SearchResultCollection searchresultcollection = mySearcher.FindAll();

                DirectoryEntry ADentry = searchresultcollection[0].GetDirectoryEntry();

                Console.WriteLine("samaccountname: " + ADentry.Properties["samaccountname"].Value.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            Console.WriteLine("samaccountname: " + samaccountname);
            Console.ReadLine();
        }
    }

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        {
        }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}

Ответы [ 2 ]

1 голос
/ 22 января 2012

Многие API-интерфейсы .NET не учитывают ваше ручное олицетворение, например, запросы LDAP, которые вы заметили.Поэтому вместо этого вам нужно использовать конструкторы перегрузки DirectoryEntry,

http://msdn.microsoft.com/en-us/library/bw8k1as4.aspx

http://msdn.microsoft.com/en-us/library/wh2h7eed.aspx

0 голосов
/ 12 июля 2014

Ошибка (0x80004005): неопределенная ошибка

У меня возникла проблема с подключением к удаленным окнам, аутентифицированным с ошибкой Ошибка (0x80004005): Ошибка не указана. Я решил следующим образом:

//Define path
//This path uses the full path of user authentication
String path = string.Format("WinNT://{0}/{1},user", server_address, username);
DirectoryEntry deBase = null;
try
{
    //Try to connect with secure connection
    deBase = new DirectoryEntry(path, username, _passwd, AuthenticationTypes.Secure);

    //Connection test
    //After test define the deBase with the parent of user (root container)
    object nativeObject = deBase.NativeObject;
    deBase = deBase.Parent;

}
catch (Exception ex)
{
    //If an error occurred try without Secure Connection
    try
    {
        deBase = new DirectoryEntry(path, username, _passwd);

        //Connection test
        //After test define the deBase with the parent of user (root container)
        object nativeObject = deBase.NativeObject;
        deBase = deBase.Parent;
        nativeObject = deBase.NativeObject;

    }
    catch (Exception ex2)
    {
        //If an error occurred throw the error
        throw ex2;
    }
}

Надеюсь, это поможет. Хельвио Джуниор www.helviojunior.com.br

...