Tuesday 3 November 2015

IIS and Impersonation

Setting
<authentication mode="Windows" />
<identity impersonate="true"/>

on an IIS application will set the thead to run under the identity of the current user. All calls, such as file writing, writing to the event logs, will run under the identity of the current authenticated user. In this case you need to ensure that the folders and event logs allow the current user (indeed all potential users that may authenticate) to perform the task.

Note also, that if you want to pass on those credentials, for example to call another webservice or Website that requires Windows Authentication, then you need to enable delegation. By default the first Website is only allowed to impersonate, but not pass on the credentials to a 3rd party. To allow this you need to configure delegation for the Website in Active Directory. You also need to ensure the client can authenticate using Kerberos (this may involve setting the trust levels for the URL).



However, I found running the application under the context of the user at all times is troublesome. For example, Log4net fails to write to a network share, despite me setting Everyone=Full Permission.

It is probably far better to allow the Web application to run under the service account as normal, but impersonate the user only for the short call to the back-end Web service.

To do this, set
<authentication mode="Windows" />
<identity impersonate="false"/>

this ensures the application runs under the service account. Then write the code to impersonate the user.

var windowsId = (WindowsIdentity)User.Identity;
            WindowsImpersonationContext windowsContext = null;

            try
            {
                // Start impersonating
                // http://msdn.microsoft.com/en-us/library/ff647404.aspx
                windowsContext = windowsId.Impersonate();

                result = service.ValidateTrades(trades);
            }
            catch (Exception error)
            {
            }
            finally
            {
                // Revert impersonation
                if (windowsContext != null)
                {
                    windowsContext.Undo();
                }                
            }

No comments:

Post a Comment