Search code examples
c#asp.netbatch-fileasp.net-2.0impersonation

Running a Batch (which run an exe) from ASP .NET


I have the following code inside an ASP .NET 2.0 webapp, which call an external bat:

using (Process process = new Process()) 
{
    process.StartInfo.FileName = command;
    process.StartInfo.Arguments = args;
    process.Start();

    process.WaitForExit();
    int exitCode = process.ExitCode;
}

This code works fine and the batch script is successfully executed.

If i try to call an external executable (no matter what the exe does) from inside the batch script, I got an error related to user privileges (unfortunately I have not the full error message, but it looks like that the ASP .NET User cannot run the executable.

I have tried to specify this parameter in order to use a specified user:

process.StartInfo.UserName = "User";
process.StartInfo.Password = this.ConvertToSecureString("Password");
process.StartInfo.UseShellExecute = false;

but the process just hangs forever.


Solution

  • You can try with this old article from Microsoft, it describe a way to use the Windows API, for impersonation purpose, in ASP.NET, don't be afraid about the spaghetti code you will see, just implement your call inside the:

    public void Page_Load(Object s, EventArgs e)
    {
        if(impersonateValidUser("username", "domain", "password"))
        {
            //Insert your code that runs under the security context of a specific user here.
            undoImpersonation();
        }
        else
        {
            //Your impersonation failed. Therefore, include a fail-safe mechanism here.
        }
    }