2012-06-26 21 views
0

首先,我很抱歉這是重複的,但我確實無法在任何地方找到類似的問題。只有當用戶在web.config中指定時,ASP.NET模擬才起作用

情況是我試圖使用asp.net中的模擬功能來檢索位於網絡目錄中的文件。當我指定在web.config中的用戶,它工作正常:

<identity impersonate="true" userName="contoso\Jane" password="********" /> 

然而,當我嘗試使用下面,我收到一個提示,登錄到網站,這我從來沒有能夠成功地做到。

<identity impersonate="true"/> 

我後面的示例的理解是,它會嘗試與任何人正在瀏覽的頁面(通過Windows身份驗證)的Windows憑據來冒充。這是不正確的?

我應該注意到,我確實有Windows身份驗證在應用程序的其他區域正常工作。

感謝

編輯

我還要提到的,這是對II6運行......它只是「感覺」像一個配置問題...

+0

你在第二個有Context.User什麼例? – Tisho

+0

它按預期返回登錄用戶。 – chad

+0

因此Context.User的類型是WindowsPrincipal? – Tisho

回答

0

我會去一個其他方式與一個額外的類Impersonate.cs和你需要一個用戶,一個密碼和一個域。

Imperosnate.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Security; 
using System.Security.Principal; 
using System.Runtime.InteropServices; 
using System.IO; 
using System.Text; 

using System.Web; 

namespace [YourProgramName] //You must change it 
{ 
    public class Impersonate 
    { 

     [DllImport("advapi32.dll", SetLastError = true)] 
     private static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, 
              int dwLogonType, int dwLogonProvider, out int phToken); 

     [DllImport("kernel32.dll")] 
     private static extern int FormatMessage(int dwFlags, string lpSource, int dwMessageId, int dwLanguageId, 
               StringBuilder lpBuffer, int nSize, string[] Arguments); 


     private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8; 
     private const int LOGON32_PROVIDER_DEFAULT = 0; 
     private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000; 

     private static WindowsImpersonationContext winImpersonationContext = null; 

     public static void ImpersonateUser(string domain, string userName, string password) 
     { 

      //Benutzer einloggen 
      int userToken = 0; 

      bool loggedOn = (LogonUser(userName, domain, password, LOGON32_LOGON_NETWORK_CLEARTEXT, 
             LOGON32_PROVIDER_DEFAULT, out userToken) != 0); 

      if (loggedOn == false) 
      { 
       int apiError = Marshal.GetLastWin32Error(); 
       StringBuilder errorMessage = new StringBuilder(1024); 
       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, null, apiError, 0, errorMessage, 1024, null); 
       throw new Exception(errorMessage.ToString()); 
      } 

      WindowsIdentity identity = new WindowsIdentity((IntPtr)userToken); 
      winImpersonationContext = identity.Impersonate(); 

     } 

     public static void UndoImpersonation() 
     { 
      if (winImpersonationContext != null) 
      { 
       winImpersonationContext.Undo(); 
      } 
     } 

    } 
} 

用它在你的程序:

string Admin = Properties.Settings.Default.Admin; 
     string AdminPassword = Properties.Settings.Default.AdminPassword; 
     string Domain = Properties.Settings.Default.Domain; 

     Impersonate.ImpersonateUser(Domain , Admin , AdminPassword); 

           //Your Code as the new User 


         Impersonate.UndoImpersonation(); 

希望這是你搜索什麼^^

相關問題