Impersonation example
I can check if the user domain administrator is the following lines of code:
using (Impersonation im = new Impersonation(UserName, Domain, Password)) { System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); bool isDomainAdmin = identity.IsDomainAdmin(Domain, UserName, Password); if (!isDomainAdmin) {
where IsDomainAdmin is the extension method
public static bool IsDomainAdmin(this WindowsIdentity identity, string domain, string userName, string password) { Domain d = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, domain, userName, password)); using (DirectoryEntry de = d.GetDirectoryEntry()) { byte[] domainSIdArray = (byte[])de.Properties["objectSid"].Value; SecurityIdentifier domainSId = new SecurityIdentifier(domainSIdArray, 0); SecurityIdentifier domainAdminsSId = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, domainSId); WindowsPrincipal wp = new WindowsPrincipal(identity); return wp.IsInRole(domainAdminsSId); } }
But when the IsDomainAdmin method is called, it tries to write some files to% LOCALAPPDATA% for the impersonated user, and if the program is not running as an administrator, it throws an exception
Failed to load file or assembly 'System.DirectoryServices, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a' or one of its dependencies. Either the required impersonation level was not or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542)
source share