public static WindowsIdentity CreateWindowsIdentity( string userName, string domainName, SecureString password, bool isManagedServiceAccount, NativeHelper.LogonType logonType = NativeHelper.LogonType.LOGON32_LOGON_NETWORK_CLEARTEXT, NativeHelper.LogonProvider logonProvider = NativeHelper.LogonProvider.LOGON32_PROVIDER_DEFAULT) { IntPtr passwordPtr = IntPtr.Zero; try { #if !DotNetCoreClr passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(password); #else passwordPtr = SecureStringMarshal.SecureStringToGlobalAllocUnicode(password); #endif return(AccountHelper.CreateWindowsIdentity( userName, domainName, passwordPtr, isManagedServiceAccount, logonType, logonProvider)); } finally { Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); } }
public static WindowsIdentity CreateWindowsIdentity( string userName, string domainName, string password, bool isManagedServiceAccount, NativeHelper.LogonType logonType = NativeHelper.LogonType.LOGON32_LOGON_NETWORK_CLEARTEXT, NativeHelper.LogonProvider logonProvider = NativeHelper.LogonProvider.LOGON32_PROVIDER_DEFAULT) { IntPtr passwordPtr = IntPtr.Zero; try { passwordPtr = Marshal.StringToHGlobalUni(password); return(AccountHelper.CreateWindowsIdentity( userName, domainName, passwordPtr, isManagedServiceAccount, logonType, logonProvider)); } finally { Marshal.FreeHGlobal(passwordPtr); } }
public static WindowsIdentity CreateWindowsIdentity( string userName, string domainName, IntPtr password, bool isManagedServiceAccount, NativeHelper.LogonType logonType = NativeHelper.LogonType.LOGON32_LOGON_NETWORK_CLEARTEXT, NativeHelper.LogonProvider logonProvider = NativeHelper.LogonProvider.LOGON32_PROVIDER_DEFAULT) { IntPtr handle = IntPtr.Zero; try { if (isManagedServiceAccount) { logonType = NativeHelper.LogonType.LOGON32_LOGON_SERVICE; } bool success = NativeHelper.LogonUser( userName, domainName, password, logonType, logonProvider, out handle); if (success) { return(new WindowsIdentity(handle)); } else { int win32Err = Marshal.GetLastWin32Error(); throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, win32Err == InvalidUserNameOrPasswordError ? "Incorrect user name or password. UserName: {0}, DomainName: {1}, IsManagedServiceAccount={2}. Error:{3}" : "Failed to get AccessToken. UserName: {0}, DomainName: {1}, IsManagedServiceAccount={2}. Error:{3}", userName, domainName, isManagedServiceAccount, win32Err)); } } finally { if (handle != IntPtr.Zero) { NativeHelper.CloseHandle(handle); } } }