asp.net(C#)中实现身份模拟 |
在一些应用场景中,需要以较高的帐户权限来执行一段程序从而实现某个功能。比如:在
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 co nst 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.Iden tityAnalogue(); if( ia.ImpersonateValidUser( userName , domain , password ) ){ // 执行特定功能的代码段,参数 domain 可为空 "" } // 最后将用户上下文恢复为当前表示的 Windows 用户 ia.UndoImpersonation() ; |