Connecting to a database using Windows authentication using different credentials using C #

Maybe someone can help me here. I am writing a program in C # to connect to a database on a remote server. The server in question uses Windows authentication. I am also not a server administrator.

In any case, I must use different credentials to connect to the server using SQL Server Management Studio. Therefore, I use runas.exe to connect.

Basically, something along the lines of:

runas.exe / netonly / user: DIFFERENT_DOMAIN \ SAME_USERNAME "C: \ Program Files (x86) \ Microsoft SQL Server \ 100 \ Tools \ Binn \ VSShell \ Common7 \ IDE \ Ssms.exe"

Using runas.exe is the only way to connect to the database, if I try to start ssms without runas, I will not connect at all.

So now my question. In the program that I am doing in C #. How can I connect my program to the same database using different credentials without using runas.exe?

I tried using:

Sqlconnection sc = new Sqlconnection(); sc.ConnectionString = "Data Source= myServer;Initial Catalog= myDB;Integrated Security=true"; sc.Open(); 

But I just get a "Login failed for user". The user is not associated with a reliable SQL Server connection. "

If I use the above code and Runas.exe with the correct credentials. It will work fine and connect. However, I do not want to use it.

Does anyone know how to make the connection work?

+4
source share
2 answers

You can impersonate a domain user from your C # code. There are several examples related to this issue:

Impersonating Windows with C #

+3
source

Thanks for telling us about Windows Impersonation! After looking at this and working on Windows Impersonation, I came across

 [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool CreateProcessWithLogonW( String userName, String domain, String password, LogonFlags logonFlags, String applicationName, String commandLine, CreationFlags creationFlags, UInt32 environment, String currentDirectory, ref StartupInfo startupInfo, out ProcessInformation processInformation); 

And we will see the entry flag in LOGON_NETCREDENTIALS_ONLY. It worked great.

+1
source

Source: https://habr.com/ru/post/1385448/


All Articles