ASP.NET PowerShell Impersonation

2019-03-20 21:10发布

问题:

I have developed an ASP.NET MVC Web Application to execute PowerShell scripts.

I am using the VS web server and can execute scripts fine.

However, a requirement is that users are able to execute scripts against AD to perform actions that their own user accounts are not allowed to do.

Therefore I am using impersonation to switch the identity before creating the PowerShell runspace:

            Runspace runspace = RunspaceFactory.CreateRunspace(config);

        var currentuser = WindowsIdentity.GetCurrent().Name;

        if (runspace.RunspaceStateInfo.State == RunspaceState.BeforeOpen) {
            runspace.Open();
        }

I have tested using a domain admin account and I get the following exception when calling runspace.Open():

Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. Exception Details: System.Security.SecurityException: Requested registry access is not allowed.

The web application is running in full trust and I have explicitly added the account I am using for impersonation to the local administrators group of the machine (even though the domain admins group was already there).

I'm using advapi32.dll LogonUser call to perform the impersonation in a similar way to this post (http://blogs.msdn.com/webdav_101/archive/2008/09/25/howto-calling-exchange-powershell-from-an-impersonated-thead.aspx)

Any help appreciated as this is a bit of a show stopper at the moment.

Thanks Ben

回答1:

Does this blog post help? Comes straight from the PowerShell devs. Essentially, PowerShell starts a new thread to run the pipeline, and since .NET2.0 doesn't allow the thread to use the impersonation from the calling thread, it fails.

http://blogs.msdn.com/powershell/archive/2007/09/10/impersonation-and-hosting-powershell.aspx