[英]how to send local user credential through code so that window app can run with local user context
I have a C# winform application which I want to impersonate with a local window user. 我有一个C#winform应用程序,我想用本地窗口用户模拟。 I can run the exe
run as different user and can send the local user credential, 我可以以其他用户身份运行exe
并可以发送本地用户凭据,
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Question - how to send the credential for local user through code
so that whenever the application runs, it's should run with that user context? 问题-如何通过code
发送本地用户的凭据,以便每当应用程序运行时,都应使用该用户上下文运行凭据? Any example code appreciate. 任何示例代码表示赞赏。 Thanks! 谢谢!
I dont know a direct way to do this, i found a solution though, it isnt really pretty but it would do the job 我不知道执行此操作的直接方法,尽管我找到了解决方案,它确实不是很漂亮,但可以完成工作
You would need 2 main things to pull this off. 您将需要两个主要的东西来实现这一目标。 First to install psexec and secondly to create a console app with this code in mind. 首先要安装psexec,其次要牢记此代码来创建控制台应用程序。 You would run the program you like as the user you like 您将以所需的用户身份运行所需的程序
using System.Diagnostics;
// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = \\computername -u user -p password "PathToYourProgram";
// Enter the executable to run, including the complete path
start.FileName = psexec.exe;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
proc.WaitForExit();
// Retrieve the app's exit code
exitCode = proc.ExitCode;
}
this code is taken from Launching an application (.EXE) from C#? 此代码取自从C#启动应用程序(.EXE)?
I'm able to run the winform in local user context, here I did impersonate code. 我可以在本地用户上下文中运行winform,在这里我模拟了代码。 Refer this article, https://docs.microsoft.com/en-us/dotnet/api/system.security.principal.windowsimpersonationcontext?redirectedfrom=MSDN&view=netframework-4.7.2 请参阅这篇文章, https://docs.microsoft.com/zh-cn/dotnet/api/system.security.principal.windowsimpersonationcontext?redirectedfrom = MSDN&view = netframework-4.7.2
and here is my code, running Form1()
under impersonation, 这是我的代码,在模拟下运行Form1()
,
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Security;
namespace WindowsFormsApp1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
[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 extern static bool CloseHandle(IntPtr handle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
[STAThread]
static void Main()
{
try
{
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(PUT_YUR_LOCAL_USER_NAME, PUT_YOUR_MACHINE_HOST_NAME_OR_DOMAIN_NAME, PUT_YOUR_PASSWORD, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out SafeTokenHandle safeTokenHandle);
//Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
MessageBox.Show(string.Format("LogonUser failed with error code : {0}", ret));
throw new System.ComponentModel.Win32Exception(ret);
}
using (safeTokenHandle)
{
// Use the token handle returned by LogonUser.
using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
{
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Exception occurred. " + ex.Message);
}
}
}
}
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.