您的位置:首页 > 编程语言 > ASP

asp.net(C#)中实现身份模拟(转贴)

2008-03-04 11:15 531 查看
asp.net(C#)中实现身份模拟
[align=center][/align]
在一些应用场景中,需要以较高的帐户权限来执行一段程序从而实现某个功能。比如:在ASP.NET程序中,如果需要写入一段日志到文件中,但空间提供商并没有给指定目录asp.net帐户写权限,就可以用到此方法了,前提是你要知道他们给你开的用户及密码,一般都是FTP帐号及密码。当然,最简单的办法就是找空间商开通此权限。上面的情况可能不是必须这样做的,但以编程方法实现身份模拟的方法还是很有的!
代码如下:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace FCMS.Framework.Utility
{
///
/// Windows身份模拟。
///
public class IdentityAnalogue {
//模拟指定用户时使用的常量定义
/**////
///
///
public const int LOGON32_LOGON_INTERACTIVE = 2;
/**////
///
///
public const int LOGON32_PROVIDER_DEFAULT = 0;
/**////
///
///
WindowsImpersonationContext impersonationContext;
//win32api引用
/**//// mmary>
///
///
///

///

///

///

///

///

///
[DllImport("advapi32.dll")]
public static extern int LogonUserA(string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
/**////
///
///
///

///

///

///
[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
/**////
///
///
///
[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]
public static extern bool RevertToSelf();
/**////
///
///
///

///
[DllImport("kernel32.dll",CharSet=CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
/**////
///
///
public IdentityAnalogue() {
}

//模拟指定的用户身份
/**////
///
///
///

///

///
ram>
///
public bool ImpersonateValidUser(string userName,string domain,string password) {
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if(RevertToSelf()) {
if(LogonUserA(userName,domain,password,2,0,ref token)!=0) {
if(DuplicateToken(token,2,ref tokenDuplicate)!=0) {
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if(impersonationContext!=null) {
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if(token!= IntPtr.Zero)
CloseHandle(token);
if(tokenDuplicate!=IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
//取消模拟
/**////
///
///
public void UndoImpersonation() {
impersonationContext.Undo();
}
}
}
使用方法:
//在你执行特定功能的代码前先验证模拟帐户:
FCMS.Framework.Utility.IdentityAnalogue ia = new FCMS.Framework.Utility.IdentityAnalogue();
if( ia.ImpersonateValidUser( userName , domain , password ) ){
//执行特定功能的代码段,参数domain可为空""
}
//最后将用户上下文恢复为当前表示的Windows用户
ia.UndoImpersonation();

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: