如何模拟登录用户并访问unc文件夹?

时间:2011-07-08 12:31:08

标签: c# impersonation 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,无所谓,就像一个魅力!

问题是你必须提供密码,因为它是我要检查的登录用户权限,我无法提供。

有谁知道为什么应用程序会像这样?是否需要设置一些配置设置?

1 个答案:

答案 0 :(得分:0)

  

Web应用程序以特定方式运行   身份,这个身份是基于   本地计算机上的用户帐户或   域。

     

应用程序使用此标识   当它访问磁盘上的资源或   服务。

     

如果该帐户没有权利   资源,Web应用程序将   无法使用该资源。

     

模仿是网络的所在   应用假定不同   来自默认的身份

     

可以将模拟配置为   用于Web应用程序   通过添加标签启动   到web.config文件。模拟   也可以动态实现   代码,以便它可以打开和   根据需要关闭。

来自ASP.NET Identity and Impersonation Different Impersonation

请检查web.config和IIS配置,确保您模仿正确的用户。