使用特定用户帐户运行Windows应用程序

3
我需要确保我的Windows应用程序(WinForm而不是控制台)在特定用户帐户下运行(换句话说,任何用户都可以登录到机器上,但.exe将始终作为指定的用户执行)。
这是否可以通过编程实现?如果可以,如何实现?

你打算如何作为用户进行身份验证?你会在某个地方存储密码吗? - Simon Mourier
是的,我可以将pwd存储在应用程序可以访问的某个地方。或者如果需要,可以硬编码它。 - Robert
2个回答

4
您可以这样启动应用程序:
ProcessStartInfo psi = new ProcessStartInfo(myPath);
psi.UserName = username;

SecureString ss = new SecureString();
foreach (char c in password)
{
 ss.AppendChar(c);
}

psi.Password = ss;
psi.UseShellExecute = false;
Process.Start(psi);

1

你可以在你的应用程序中做一件事情,就是检查你是否作为所需用户运行,如果不是,则创建一个新的应用程序实例作为另一个用户。第一个实例将退出。

要检查你正在以哪个用户身份运行,你可以改编这里的解决方案,使进程查询其令牌信息。

使用CreateProcessWithLogonW,传递LOGON_WITH_PROFILE登录标志。你要登录的用户必须具有适当的策略设置,才能允许交互式登录。

编辑:现在你已经表明你正在使用.NET,下面是你应该如何做:

首先,您需要找出当前正在运行的用户。使用System.Security.Principal命名空间中的WindowsIdentity类。调用其GetCurrent方法以获取您正在运行的用户的WindowsIdentity对象。Name属性将为您提供实际的用户名。

在您的ProcessStartInfo对象中,设置LoadUserProfile=trueFileName字段,可能还有Arguments字段,UserNamePassword字段,可能还有Domain字段,并设置UseShellExecute=false。 然后调用Process.Start(),传入您的ProcessStartInfo对象。
这是我拼凑的一个示例,但我没有安装C#编译器来测试它:
using System;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;

// Suppose I need to run as user "foo" with password "bar"

class TestApp
{
    static void Main( string[] args )
    {
        string userName = WindowsIdentity.GetCurrent().Name;
        if( !userName.Equals( "foo" ) ) {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "testapp.exe";
            startInfo.UserName = "foo";

            SecureString password = new SecureString();
            password.AppendChar( 'b' );
            password.AppendChar( 'a' );
            password.AppendChar( 'r' );
            startInfo.Password = password;

            startInfo.LoadUserProfile = true;
            startInfo.UseShellExecute = false;

            Process.Start( startInfo );    
            return;
        }
        // If we make it here then we're running as "foo"
    }
}

谢谢提供的链接。我正在使用C#,但明天会详细查看建议的解决方案。 - Robert
1
请查看我的编辑,我已添加了一些与.NET相关的内容。 - Aaron Klotz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接