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:

   <authentication mode="Windows"/>
   <identity impersonate="false"/>

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))
     ctx = wi.Impersonate();

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

     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.

Comments (0)

Skip to main content