假冒使用者的方法:
說明:在用ASP.NET時常因為安全問題而沒有許可權做某事,但有時我們又確實要使用到這些許可權時,我們就應該給這些使用者授予一些許可權,而下面我們就來使用假冒來授予許可權.
下面的是 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>
/// 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);
//登入假冒使用者
//CompName是該電腦的使用者名稱,CompPassword是該使用者的密碼
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;
}
}
//登出假冒使用者
public void ChangeRoleOUT()
{
try
{
impersonationContext.Undo();
}
catch{}
}
}
}
使用方法,下面的是ASP.NET檔案 ChangeUser.aspx
<%@ Page language="c#" AutoEventWireup="false"%>
<%@ Import Namespace= "com.todayisp.identity"%>//記得使用該命名空間
<%
string UserName = Request.Params["UserName"];
string Password = Request.Params["Password"];
if (UserName == null && Password == null)
{
Response.Write("error:使用者名稱和密碼為空白.");
return;
}
//假冒身份開始
IDEN Identity = new IDEN();
bool In = Identity.ChangeRoleIN(UserName,PasswordKey);
if (!In){
Response.Write("error:變更使用者權限失敗");
return;
//假冒身份結束
Identity.ChangeRoleOUT();
%>