Question

There is a long back story to this, but to summarize I am trying to create a SQL Server connection in my VB program to automatically run some queries and display results. I have been able to do this easily when the server is on my network in the past. Now my company is moving to a hosted server and I am running into issues.

I can successfully connect to the server using SSMS when I use the RUNAS command:

    runas /netonly /user:[network domain]\[username] "C:\Program Files (x86)\Microsoft SQLServer\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe"

But I can't figure out how to set the VB program SQL connection string in similar fashion.

I know I can use Integrated Security = SSPI to specify Windows Authentication, but I need to pass the username and password as well, along with the network/domain information.

When I try to do this I get a "Login Failed for User..." message or "The Login is from an untrusted domain and cannot be used with Windows authentication" with Integrated Security=SSPI.

There is something about Windows Impersonation but I haven't been able to get a grip on how it would work here.

If this is possible the changes need to be almost entirely on my end, as the hosting company is very ...picky... about making any changes to their environments or settings.

I appeal to the wisdom of the internet for answers!

Extra Facts: SQL Server 2008, Windows 7, Microsoft Visual Studio 2013, Windows Form Program

Was it helpful?

Solution

There is a good knowledge base article about that for ASP.NET, but I think the code solution also works on other platforms:

Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext
Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity

currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity)
impersonationContext = currentWindowsIdentity.Impersonate()

'Insert your code that runs under the security context of the authenticating user here.

impersonationContext.Undo()

Inside, you can run you connection with SSPI defined as you normally would.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top