2011-07-08 41 views
2

我在冒充登錄的用戶時遇到問題,然後訪問unc文件。我一直在使用此示例代碼嘗試:如何模擬登錄用戶並訪問unc文件夾?

using System.Security.Principal; 
... 
// Obtain the authenticated user's Identity 
WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity; 
WindowsImpersonationContext ctx = null; 
try 
{ 
    // Start impersonating 
    ctx = winId.Impersonate(); 
    // Now impersonating 
    // Access resources using the identity of the authenticated user 
} 
// Prevent exceptions from propagating 
catch{} 
finally 
{ 
    // Revert impersonation 
    if (ctx != null)  
     ctx.Undo(); 
} 
// Back to running under the default ASP.NET process identity 

如果我嘗試在評論說,使用經過驗證的用戶它的工作原理完全,因爲它應該的身份訪問資源訪問本地文件。但是,如果我嘗試使用UNC的某個文件服務器上的某個文件(如\\ ServerName \ Share \ FileName.txt)執行相同的操作,則模擬的帳戶擁有足夠的權限並不重要。應用程序拋出一個異常,說ASP.NET帳戶沒有足夠的權限。

我也嘗試使用非託管代碼來執行模擬,然後它工作!本地文件或UNC無關緊要,就像一個魅力!

問題是你必須提供密碼,因爲它是登錄用戶權限我想檢查我不能提供。

有誰知道爲什麼應用程序的行爲像這樣?是否需要設置一些配置設置?

+2

所以爲了防止異常傳播你甚至沒有趕上並記錄他們!? cooool! –

+0

您正在模擬ASP.NET帳戶...不是當前用戶帳戶。什麼是你的認證模式,你有指定模擬web.config? – 2GDev

+0

@Davide:我認爲這是一個示例代碼...檢查這裏:http://stackoverflow.com/questions/4334665/steps-to-enable-double-hop-delegation-in-iis7-windows-2008,和在這裏http://stackoverflow.com/questions/983443/windowsidentity-winid-windowsidentityhttpcontext-current-user-identity-how-t並且這裏是來源:http://msdn.microsoft.com/en-us/library/ms998351的.aspx#paght000023_impersonatingbyusingwindowsidentity – 2GDev

回答

0

Web應用程序與特定的身份 運行,這個身份是基於本地計算機或 域上 用戶帳戶。

當它訪問磁盤或 服務上的資源時,應用程序使用此標識 。

如果該帳戶沒有 資源的權限,則Web應用程序將無法使用該資源 。

模擬是Web 應用程序假定從默認

模擬可以被配置爲用於在 啓動web應用 不同 身份,通過添加標籤 到web.config文件。冒充 也可以在 代碼中動態實現,這樣它可以根據需要打開並關閉 。

ASP.NET Identity and Impersonation Different Impersonation

因此,檢查你的web.config和IIS配置,並確保你模仿正確的用戶。