簡體   English   中英

如何通過代碼發送本地用戶憑據,以便窗口應用程序可以在本地用戶上下文中運行

[英]how to send local user credential through code so that window app can run with local user context

我有一個C#winform應用程序,我想用本地窗口用戶模擬。 我可以以其他用戶身份運行exe並可以發送本地用戶憑據,

 static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

在此處輸入圖片說明

問題-如何通過code發送本地用戶的憑據,以便每當應用程序運行時,都應使用該用戶上下文運行憑據? 任何示例代碼表示贊賞。 謝謝!

我不知道執行此操作的直接方法,盡管我找到了解決方案,它確實不是很漂亮,但可以完成工作

您將需要兩個主要的東西來實現這一目標。 首先要安裝psexec,其次要牢記此代碼來創建控制台應用程序。 您將以所需的用戶身份運行所需的程序

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;
}

此代碼取自從C#啟動應用程序(.EXE)?

我可以在本地用戶上下文中運行winform,在這里我模擬了代碼。 請參閱這篇文章, https://docs.microsoft.com/zh-cn/dotnet/api/system.security.principal.windowsimpersonationcontext?redirectedfrom = MSDN&view = netframework-4.7.2

這是我的代碼,在模擬下運行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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM