我有一个在 IIS 上运行的 ASP.NET C# 应用程序。
某些操作要求我使用 Directory.EnumerateFiles
读取本地放置在系统上的文件。这在我调用该函数时有效,因为我的 Windows 用户可以访问这些文件,但当另一个用户调用同一页面时则不能。
我检查了 WindowsIdentity.GetCurrent().Name
,我确实看到 CompanyName\MyName
是当前用户。这些文件包含敏感数据,我不希望所有用户都具有读取权限,即使他们在远程系统上也是如此。
在我看来,我想专门为我的 IIS 应用程序授予读取文件夹的权限,并以某种方式从 IIS 应用程序而不是从执行请求的当前用户调用函数 Directory.EnumerateFiles(授权已在应用程序本身)。
这是否可行,如果可行,如何实现?
解决方案
我最终使用了这个答案:Can I turn off impersonation just in a couple instances :
using (WindowsIdentity.Impersonate(IntPtr.Zero))
{
//Directory.EnumerateFiles(...)
//File.ReadAllText(...)
}
另外,我为以下用户授予了文件夹访问权限:IIS APPPOOL\MyAppPoolName
最佳答案
您必须使用某种模拟。您可以在此处找到选项:https://support.microsoft.com/en-us/help/306158/how-to-implement-impersonation-in-an-asp-net-application
Impersonate the IIS authenticated account or user
Impersonate a specific user for all the requests of an ASP.NET application
Impersonate the authenticating user in code Impersonate a specific user in code
所有请求的示例配置
<identity impersonate="true"
userName="domain\user"
password="password" />
域用户应具有所需的访问权限。
如果您想使用第三个选项,请检查 this answer here它使用以下内容来模拟每个代码块:
try
{
if (!WindowsIdentity.GetCurrent().IsSystem)
{
using (WindowsIdentity.Impersonate(IntPtr.Zero))
{
// Do stuff here
}
}
}
catch { }
关于c# - 以本地系统而非当前用户身份读取本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59355300/