Impersonation of a user without using Identity impersonation.

July 31, 2007

There might be several possible secenarios where you might need to forcefully impersonate a user which is valid on some domain but without using identity impersonation.

Looking back in time of the Win32 apis, here is how it can be achieved:

The Win32 api called as LogonUser(string user, string domain, string password, LogonSessionType type, LogonProvider provider, out IntPtr token) is the question to our answer. This is a exported from advapi32.dll.

//code
using System.Security;
using System.Security.Principal; 

[DllImport(“advapi32.dll”, SetLastError = true)]
static extern bool LogonUser( string user, string domain, string password, LogonSessionType logonType, LogonProvider logonProvider, out IntPtr token);

enum LogonSessionType : uint{Interactive = 2, Network, Batch, Service, NetworkCleartext = 8, NewCredentials}enum LogonProvider : uint{
Default = 0,
// default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}

public void ImpersonateCurrentRequest(HttpContext ctxt)
{
IntPtr token = IntPtr.Zero;
bool result = LogonUser(“someusername”, “somedomain”, “somepassword”,LogonSessionType.Network,LogonProvider.Default,out token);
if (result)
{
WindowsIdentity iden = new WindowsIdentity(token);
WindowsPrincipal principal = new WindowsPrincipal(iden);
IPrincipal p = (IPrincipal)principal;
ctxt
.User = p;
CloseHandle(token);
}
}

//end code

Note this has to be done before the request is processed, so it better to call this function from a httpmodule:BeginRequest()

-Bugs!

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: