using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.IO;
using System.Configuration;
using System.Web.UI;
/// 用户模拟角色类。实现在程序段内进行用户角色模拟。
/// <example><![CDATA[使用的时候在你要执行特殊操作的代码段前面这样写:
/// IdentityImpersonation identityImpersonation = new IdentityImpersonation("administrator", "yourpassword","yourhostname");
/// identityImpersonation.BeginImpersonate();//开始管理员扮演
/// //你的特殊操作
/// ..
/// .
/// identityImpersonation.StopImpersonate(); //结束扮演]]>
/// </example>
///
public class IdentityImpersonation
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
// 要模拟的用户的用户名、密码、域(机器名)
private String _sImperUsername;
private String _sImperPassword;
private String _sImperDomain;
// 记录模拟上下文
private WindowsImpersonationContext _imperContext;
private IntPtr _adminToken;
private IntPtr _dupeToken;
// 是否已停止模拟
private Boolean _bClosed;
///<summary>
///构造函数
///</summary>
///<param name="impersonationUsername">所要模拟的用户的用户名</param>
///<param name="impersonationPassword">所要模拟的用户的密码</param>
///<param name="impersonationDomain">所要模拟的用户所在的域</param>
public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)
{
_sImperUsername = impersonationUsername;
_sImperPassword = impersonationPassword;
_sImperDomain = impersonationDomain;
_adminToken = IntPtr.Zero;
_dupeToken = IntPtr.Zero;
_bClosed = true;
}
///<summary>
///析构函数
///</summary>
~IdentityImpersonation()
{
if (!_bClosed)
{
StopImpersonate();
}
}
///<summary>
///开始身份角色模拟。
///</summary>
///<returns></returns>
const int LOGON32_LOGON_INTERACTIVE = 2;
//const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
//// logon providers
const int LOGON32_PROVIDER_DEFAULT = 0;
//const int LOGON32_PROVIDER_WINNT50 = 3;
//const int LOGON32_PROVIDER_WINNT40 = 2;
//const int LOGON32_PROVIDER_WINNT35 = 1;
public Boolean BeginImpersonate()
{
Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref _adminToken);
if (!bLogined)
{
return false;
}
Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);
if (!bDuped)
{
return false;
}
WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);
_imperContext = fakeId.Impersonate();
_bClosed = false;
return true;
}
///<summary>
///停止身分角色模拟。
///</summary>
public void StopImpersonate()
{
_imperContext.Undo();
CloseHandle(_dupeToken);
CloseHandle(_adminToken);
_bClosed = true;
}
public void SaveData(Page page,HttpResponse Response, string path)
{
bool isImpersonated = false;
try
{
if (BeginImpersonate())
{
isImpersonated = true;
//do what you want now, as the special user
// ...
string file = ConfigurationManager.AppSettings["SavePath"];
string filename = path.Substring(path.LastIndexOf("\\") + 1); //截取文件名
string serverfolder = file + @"Upload\";
//string strRamd = Guid.NewGuid().ToString("N");
string serverpath = serverfolder + filename; //指定文件保存路径
File.Copy(path, serverpath, true);
//初始化 FileInfo 类的实例,它作为文件路径的包装
FileInfo fi = new FileInfo(serverpath);
//将文件保存到本机上
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + page.Server.UrlEncode(fi.Name));
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(fi.FullName);
Response.End();
//File.Delete(serverpath);
}
}
finally
{
if (isImpersonated)
StopImpersonate();
}
}
}