1、模擬 IIS驗證的帳戶或用戶
若要在收到 ASP.NET 應用程序中每個頁的每個請求時模擬Microsoft Internet 信息服務 (IIS) 身份驗證用戶,必須在此應用程序的 Web.config 文件中包含<identity> 標記,並將 impersonate 屬性設置爲true
目前我找到的解決方法是通過System.Security.Principal.WindowsIdentity.Impersonate方法在子線程裏模擬主線程的“windows賬戶標記”從而獲得和主線程相同權限。下面是一段測試代碼:
- protected void Page_Load(object sender, EventArgs e)
- {
- //先獲得頁面執行的主線程用戶信息, 悟空註釋,悟空的博客 www.7es.cn
- System.Security.Principal.WindowsIdentity obj = System.Security.Principal.WindowsIdentity.GetCurrent();
- thread = new Thread(new ParameterizedThreadStart(proc));
- thread.Start(obj);
- }
- void proc(object obj)
- {
- System.Security.Principal.WindowsIdentity wi = (System.Security.Principal.WindowsIdentity)obj;
- try
- {
- log.Write("test 0 start" + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
- }
- catch (Exception ex)
- {
- System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "dbg.txt",
- "這裏可能無法寫入日誌,會訪問錯誤異常的,只是表示一下此處沒有權限寫入,後面模擬賬號之後才能獲得權限");
- }
- System.Security.Principal.WindowsIdentity.Impersonate(wi.Token); //模擬一下
- System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "dbg.txt",
- "ok, 這裏可以寫入日誌文件");
- }