Search code examples
sql-serveractive-directoryado.netimpersonation

ADO.NET - Connect to SQL Server with Windows Login with login and password supplied by the application


This is SQL Server 2008 R2, .NET 4.0.

In my SQL Server there is a user created with "Windows Authentication". The user exists in a Active Directory domain.

I want to make a .NET application connect to the SQL Server as this user. Inside the application, I know the user's domain, login and password, and the application has network access to the AD server.

How can I accomplish this?

I know that ASP.NET has it's AD provider and impersonation. But what I'm looking for is a really generic solution, one that should work on a plain console application. Something that I could use on console app, windows forms, asp.net, or a common business class library.

Thank you for the help!


Solution

  • I've done it using this class:

    https://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials/

    You must impersonate using LOGON32_LOGON_NEW_CREDENTIALS = 9 if the computer does not belong to the domain.

    Once impersonated, then connect to SQL using "Integrated Security=true" on the SQL Connection String.

    SqlConnection conn;
    using (new Impersonator("myUserName", "myDomain", "myPassword", LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_DEFAULT))
    {
        conn = new SqlConnection("Data Source=databaseIp;Initial Catalog=databaseName;Integrated Security=true;");
        conn.Open();
    }
    //(...) use the connection at your will.
    //Even after the impersonation context ended, the connection remains usable.