我需要确保我的WIDNOWS应用程序(WinForm的不是控制台)在一定的用户帐户下运行(换句话说,任何用户都可以到MACHING被记录,但该.exe总会按指定的用户执行)。运行Windows应用程序使用特定的用户帐户
可以这样做程式设计?如果是这样,怎么样?
我需要确保我的WIDNOWS应用程序(WinForm的不是控制台)在一定的用户帐户下运行(换句话说,任何用户都可以到MACHING被记录,但该.exe总会按指定的用户执行)。运行Windows应用程序使用特定的用户帐户
可以这样做程式设计?如果是这样,怎么样?
你可以这样开始应用:
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);
一件事,你可以在你的应用程序做的是检查您是否为所期望的用户在运行,如果没有,创建应用程序的新实例,为其他用户。第一例将退出。
检查正在运行作为用户,你可以在解决方案从here适应,这样的过程查询本身的令牌信息。
使用CreateProcessWithLogonW
,传递LOGON_WITH_PROFILE
登录标志。您正在登录的用户必须设置适当的策略才能以交互方式登录。
编辑:既然你已经表明你正在使用.NET,这里是你应该怎么做:
首先,你需要找出哪些用户当前运行的。使用System.Security.Principal
命名空间中的WindowsIdentity
类。调用它的GetCurrent
方法来获取正在运行的用户的WindowsIdentity
对象。 Name
属性将为您提供您正在运行的实际用户名。
在你ProcessStartInfo
对象,设置LoadUserProfile = true
,在FileName
场,可能是Arguments
领域,UserName
和Password
领域,可能是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 2011-05-20 04:59:30
请参阅我的编辑,我添加了一些与.NET相关的内容。 – 2011-05-20 19:42:10
你如何意图作为用户进行身份验证?你会在什么地方存储密码? – 2011-05-19 17:30:35
是的,我可以将pwd存储在应用可以访问的地方。或者,如果需要,可以硬编码。 – Robert 2011-05-20 04:58:59