Udostępnij za pośrednictwem


WindowsImpersonationContext

Connecting to a database on a remote SQL Server with the end-user credentials requires that you are impersonating the user in code.

Start by ensuring that your web.config does not include impersonation:

<system.web>
   <authentication mode="Windows"/>
   <identity impersonate="false"/>
</system.web>

Next modify the section of your code where you are accessing ressources on behalf of the end-user.

The concept to the solution is described here but to make the sample more relevant for the described scenario I have extended the sample with a few more lines of code:

String connectionString = WebConfigurationManager.ConnectionStrings["HrWeb"].ConnectionString;
WindowsIdentity wi =  (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext ctx = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
   try
   {
     ctx = wi.Impersonate();
     connection.Open();

     // use the connection to the database on behalf of the end-user

     connection.Close();
    }
    finally
    {
     ctx.Undo();
     ctx.Dispose();
     ctx = null;
     }
}

(Make sure that you are completing the errorhandling before going into production with this code.)

To make the solution as secure as possible you should seek to limit the scope where you impersonating the end-user, and you should also ensure that any input from the end-user is properly validated to avoid SQL Injection.