Methods for impersonating users:
Note: ASP is used. net often does not have the permission to do something because of security issues, but sometimes we really need to use these permissions, we should grant these users some permissions, next we will use counterfeiting to grant permissions.
Below is iden. CS
Using system;
Using system. Web. Security;
Using system. Security. Principal;
Using system. runtime. interopservices;
Using system. Security. cryptography;
Using system. IO;
Using system. text;
Namespace com. todayisp. Identity
{
/// <Summary>
/// Summary of iden.
/// </Summary>
///
Public class iden
{
Public const int logon32_logon_interactive = 2;
Public const int logon32_provider_default = 0;
Public const string computername = "localhost ";
Windowsimpersonationcontext impersonationcontext;
[Dllimport ("advapi32.dll", charset = charset. Auto, setlasterror = true)]
Public static extern int logonuser (string lpszusername,
String lpszdomain,
String lpszpassword,
Int dwlogontype,
Int dwlogonprovider,
Ref intptr phtoken );
[Dllimport ("advapi32.dll", charset = system. runtime. interopservices. charset. Auto, setlasterror = true)]
Public extern static int duplicatetoken (intptr htoken,
Int impersonationlevel,
Ref intptr hnewtoken );
// Log on to a fake user
// Compname is the user name of the computer, and comppassword is the user's password
Public bool changerolein (string compname, string comppassword)
{
Try
{
If (compname = NULL) return false;
If (comppassword = NULL) return false;
Windowsidentity tempwindowsidentity;
Intptr token = intptr. zero;
Intptr tokenduplicate = intptr. zero;
If (logonuser (compname, computername, comppassword, logon32_logon_interactive, logon32_provider_default, ref token )! = 0)
{
If (duplicatetoken (token, 2, ref tokenduplicate )! = 0)
{
Tempwindowsidentity = new windowsidentity (tokenduplicate );
Impersonationcontext = tempwindowsidentity. Impersonate ();
If (impersonationcontext! = NULL)
Return true;
Else
{
Return false;
}
}
Else
{
Return false;
}
}
Else
{
Return false;
}
}
Catch
{
Return false;
}
}
// Log out of a fake user
Public void changeroleout ()
{
Try
{
Impersonationcontext. Undo ();
}
Catch {}
}
}
}
The following is the ASP. NET file changeuser. aspx.
<% @ Page Language = "C #" autoeventwireup = "false" %>
<% @ Import namespace = "com. todayisp. Identity" %> // remember to use this namespace.
<%
String username = request. Params ["username"];
String Password = request. Params ["password"];
If (username = NULL & Password = NULL)
{
Response. Write ("error: the user name and password are empty .");
Return;
}
// Start with a fake identity
Iden identity = new iden ();
Bool in = identity. changerolein (username, passwordkey );
If (! In ){
Response. Write ("error: failed to Change User Permissions ");
Return;
// End with a fake identity
Identity. changeroleout ();
%>