If you want to impersonate a WindowsIdentity in ASP.NET you can use the Win32 LogonUser API and construct a WindowsIdentity obeject from the token and attach the token to the current thread:
try
{
// Create a token
bool result = LogonUser("User", "Domain",
"Password",
LogonSessionType.Network,
LogonProvider.Default,
out token);
if (result)
{
WindowsIdentity id = new WindowsIdentity(token);
// Begin impersonation
impersonatedUser = id.Impersonate();
// Resource access here uses the impersonated identity
}
}
finally
{
// Stop impersonation and revert to the process identity
if (impersonatedUser != null)
impersonatedUser.Undo();
// Free the token
if (token != IntPtr.Zero)
CloseHandle(token);
}
// Verify the old process identity
}
mm10
Contributor
6445 Points
1187 Posts
Re: ASP.NET Impersonation
Apr 06, 2012 10:30 PM|LINK
If you want to impersonate a WindowsIdentity in ASP.NET you can use the Win32 LogonUser API and construct a WindowsIdentity obeject from the token and attach the token to the current thread:
// Declare signatures for Win32 LogonUser and CloseHandle APIs
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string principal,
string authority,
string password,
LogonSessionType logonType,
LogonProvider logonProvider,
out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
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
}
protected void Impersonate(object sender, EventArgs e)
{
IntPtr token = IntPtr.Zero;
WindowsImpersonationContext impersonatedUser = null;
try
{
// Create a token
bool result = LogonUser("User", "Domain",
"Password",
LogonSessionType.Network,
LogonProvider.Default,
out token);
if (result)
{
WindowsIdentity id = new WindowsIdentity(token);
// Begin impersonation
impersonatedUser = id.Impersonate();
// Resource access here uses the impersonated identity
}
}
finally
{
// Stop impersonation and revert to the process identity
if (impersonatedUser != null)
impersonatedUser.Undo();
// Free the token
if (token != IntPtr.Zero)
CloseHandle(token);
}
// Verify the old process identity
}