Reputation: 724
I need to ensure that my widnows app (winform not console) runs under a certain user account (in other words any user can be logged on to the maching but the .exe will always execute as the specified user).
Can this be done programtically? If so, how?
Upvotes: 3
Views: 8997
Reputation: 11585
One thing you could do in your app is check if you're running as the desired user, and if not, create a new instance of your app as that other user. The first instance would then exit.
To check which user you are running as, you could adapt the solution from here so that the process queries itself for its token information.
Use CreateProcessWithLogonW
, passing the LOGON_WITH_PROFILE
login flag. The user you are logging in as must have the appropriate policies set to be allowed to log on interactively.
EDIT: Now that you have indicated that you are using .NET, here's how you should do it:
First you need to find out which user you are currently running as. Use the WindowsIdentity
class from the System.Security.Principal
namespace. Call its GetCurrent
method to obtain the WindowsIdentity
object for the user that you are running as. The Name
property will give you the actual user name that you are running under.
In your ProcessStartInfo
object, set LoadUserProfile = true
, the FileName
field, possibly the Arguments
field, the UserName
and Password
fields, possibly the Domain
field, and set UseShellExecute = false
. Then call Process.Start()
, passing in your ProcessStartInfo
object.
Here's a sample that I threw together, but I don't have a C# compiler installed to test it:
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"
}
}
Upvotes: 1
Reputation: 139256
You can start the application like this:
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);
Upvotes: 4