2014-07-22 47 views
9

在一個HTTP模塊,承接URL重寫,我現在用的測試用戶權限到到位於我的應用程序中的虛擬路徑:如何測試虛擬目錄的用戶權限?

// Since we are now rewriting the path we need to check again that the 
// current user has access to the rewritten path. 
// Get the user for the current request 
// If the user is anonymous or authentication doesn't work for this suffix 
// avoid a NullReferenceException in the UrlAuthorizationModule by creating 
// a generic identity. 
string virtualCachedPath = cache.GetVirtualCachedPath(); 

IPrincipal user = context.User ?? new GenericPrincipal(
    new GenericIdentity(string.Empty, string.Empty), new string[0]); 

// Do we have permission to call 
// UrlAuthorizationModule.CheckUrlAccessForPrincipal? 
PermissionSet permission = new PermissionSet(PermissionState.None); 
permission.AddPermission(
new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted)); 
bool hasPermission = 
permission.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet); 
bool isAllowed = true; 

// Run the rewritten path past the auth system again, using the result as 
// the default "AllowAccess" value 
if (hasPermission && !context.SkipAuthorization) 
{ 
    isAllowed = UrlAuthorizationModule.CheckUrlAccessForPrincipal(
             virtualCachedPath, user, "GET"); 
} 

virtualCachedPath是任何虛擬路徑例如~/app_data/cache位於同根應用程序。

http://msdn.microsoft.com/en-us/library/system.web.security.urlauthorizationmodule.checkurlaccessforprincipal(v=vs.110).aspx

然而,這將引發ArgumentException但如果對外部虛擬目錄進行測試。

[ArgumentException:不支持當前應用程序之外的虛擬路徑。 參數名稱:virtualPath]

E.g.

Example virtual directory in IIS

什麼是檢查用戶權限的虛擬目錄中的正確方法是什麼?

回答

2

我能夠成功地使用UrlAuthorizationModule.CheckUrlAccessForPrincipal方法來檢查駐留在映射爲虛擬目錄的外部目錄中的文件的訪問,當傳遞到CheckUrlAccessForPrincipal的路徑是相對URL格式的路徑( 「〜/路徑」)。相反,如果我使用文件系統約定傳遞物理路徑(「C:\ PATH \」),我會得到您描述的ArgumentException

所以我懷疑virtualCachedPath可能實際上是一個文件系統格式化的路徑,至少在引發異常的情況下。我建議您在應用程序中實施日誌記錄,以便您可以在出現異常時仔細檢查virtualCachedPath的值:

try 
{ 
    isAllowed = UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualCachedPath, user, "GET"); 
} 
catch (ArgumentException ex) 
{ 
    Trace.TraceInformation("VirtualCachedPath: {0}", virtualCachedPath); 
    throw; 
} 
+0

您是絕對正確的。我用來確定路徑的方法不正確。 –