Impersonation does not work for DirectoryServices

I am trying to execute the following code

using System.DirectoryServices; public bool HasVirtualDirectory(string serverName, string virtualDirectoryName) { try { DirectoryEntry directoryEntry = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/Root"); return directoryEntry.Children.Find(virtualDirectoryName, directoryEntry.SchemaClassName.ToString()) != null; } catch (Exception) { return false; } } 

Since I need administrator privileges on the server to execute this code, I used this class to impersonate the correct user:

 using (Impersonator impersonator = new Impersonator("username", "domain", "password")) { server.HasAccess = HasVirtualDirectory(server.HostName, virtualDirectory); } 

But I still get a COMException: access is denied . On the other hand, if I do not use impersonation, but I run the program directly with the same credentials that I used in the impersonation (using "Run as user" in the context menu), it works as expected.

Running the program as an administrator (administrator on the computer on which the program is running, but not on the server) did not change anything, an exception still occurred.

I also tried ImpersonationLevel.SecurityDelegation (= 3) instead of ImpersonationLevel.SecurityImpersonation (= 2) in the DuplicateToken call, but this did not change anything (both the regular and the administrator executing the program).

To check the issued code, I tried the following code and it worked. (the user executing the program does not have the right to create a directory, but the user who impersonated himself).

 using (Impersonator impersonator = new Impersonator("username", "domain", "password")) { Directory.CreateDirectory(@"\\servername\c$\tmp"); } 

I am using Windows 7 Professional with activated UAC. The server is Windows Server 2003 R2 SP2.

Does anyone have any ideas?

+1
source share
2 answers

Use the DirectoryEntry Constructor (String, String, String, AuthenticationTypes) , in which the username and password are returned instead of the name.

 DirectoryEntry directoryEntry = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/Root", @"domain\username", "password", AuthenticationTypes.Secure | AuthenticationTypes.Sealing); 
+2
source

Assuming you are using the Impersonator class from CodeProject, try changing the input type as described in this post from page 4 of comments:

Hi uwe

it only works for remote access from Vista when you change the logontype in the logonuser function to LOGON32_LOGON_NEW_CREDENTIALS.

const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

see LogonUser Function

Regards Uwe

0
source

Source: https://habr.com/ru/post/916593/


All Articles