如何测试虚拟目录的用户权限?

时间:2014-07-22 10:30:34

标签: c# security iis virtual-directory

在HttpModule中,在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

检查用户对虚拟目录的权限的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

当传递给UrlAuthorizationModule.CheckUrlAccessForPrincipal的路径是CheckUrlAccessForPrincipal时,我能够成功使用ArgumentException方法检查对驻留在外部目录中的文件的访问权限,该目录被映射为虚拟目录。相对的,URL格式的路径("〜/ PATH")。相反,如果我使用文件系统约定传递物理路径(" C:\ PATH \"),我会得到您描述的virtualCachedPath

所以我怀疑virtualCachedPath实际上可能是文件系统格式化路径,至少在引发异常的实例中。我建议您在应用程序中实现日志记录,以便在引发该异常时可以仔细检查try { isAllowed = UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualCachedPath, user, "GET"); } catch (ArgumentException ex) { Trace.TraceInformation("VirtualCachedPath: {0}", virtualCachedPath); throw; } 的值:

{{1}}