Reputation: 167
We have a domain boo.com and also somebody defined an alternative UPN suffix bc. There is an account created as foo @bc. I need to impersonate that account to connect to SQL Server.
This is what I do:
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
LogonUser(
"foo",//foo@bc
"boo.com",//"@bc"
"Password",
(int)LogonType.LOGON32_LOGON_INTERACTIVE,//(int)LogonType.LOGON32_LOGON_SERVICE,//(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS,//(int)LogonType.LOGON32_LOGON_NETWORK,//
(int)LogonProvider.LOGON32_PROVIDER_DEFAULT,//(int)LogonProvider.LOGON32_PROVIDER_WINNT50,//
ref m_Token);
...
Impersonation seems to work- LogonUser(...) succeeds, but my script doesn't have proper access. Depending on combination of parameters I get either
System.IO.FileLoadException:File name: 'System.Data, ...
In Sysinternals Process Monitor I can see "BAD IMPERSONATION" error.
or, if I play with LogonType and LogonProvider
System.Data.SqlClient.SqlException: 'Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.'
Is there any way to impersonate an AD account that defined with alternative UPN suffix?
Oh and if I run from under "foo" account everything works, meaning foo has all the access it needs. Unfortunately I need to run from another service account.
Thank you!!!
Upvotes: 0
Views: 234
Reputation: 167
By trial and error, this is what worked for me:
LogonUser(
"foo@bc",//username with suffix
NULL, //domain
"Password",
(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS, //logon type
(int)LogonProvider.LOGON32_PROVIDER_DEFAULT,
ref m_Token);
Console.WriteLine("Current user: " + WindowsIdentity.GetCurrent().Name);
//John Doe - person running the app
WindowsIdentity identity = new WindowsIdentity(m_Token);
identity.Impersonate();
Console.WriteLine("Current user: " + WindowsIdentity.GetCurrent().Name);
//still John Doe!! NOT foo@bc
//database access successful (Integrated Security)
surprisingly
WindowsIdentity.GetCurrent().Name
returns account name running the app before and after the impersonation. But access to database is granted anyway.
Upvotes: 0