Reputation: 63
Perhaps someone can help me out here. I'm writing a program in C# to connect to a database on a remote server. The server in question uses Windows Authentication. I'm also not the admin of the server.
In any event to connect to server using SQL Server Management Studio I have to use a different credentials. So I use the 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 the runas.exe is the only way I can connect to the database, if I try running ssms without the runas, I will not connect at all.
So now my question. In the program I'm making in C#. How can I get my program to connect to the same database using different credentials without having to use runas.exe?
I've tried using:
Sqlconnection sc = new Sqlconnection();
sc.ConnectionString = "Data Source= myServer;Initial Catalog= myDB;Integrated Security=true";
sc.Open();
But I just get "Login failed for user ''. User not associated with a trusted SQL Server Connection."
If I use the above code and Runas.exe with the correct credentials. It will work fine and connect. However I don't want to have to use it.
Anyone have any idea how to get the connection to work?
Upvotes: 5
Views: 13048
Reputation: 63
Thanks to who said about Windows Impersonation! After looking at that and googling around about Windows Impersonation, I ran into
[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 seeing the logon Flag to LOGON_NETCREDENTIALS_ONLY. It worked perfectly.
Upvotes: 1
Reputation: 7133
You can impersonate a domain user from your c# code. There are some examples linked from this question:
Upvotes: 4