c# - 以本地系统而非当前用户身份读取本地文件

标签 c# asp.net iis

我有一个在 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/

相关文章:

c# - C#无法在类中创建自定义RichTextBox

c# - 在 SQL 中将 LIKE '%' 与整数一起使用

javascript - 为 Web API URL 配置 Angularjs 路由

c# - 如何使用Windows Azure实现URL重写?

ASP.NET Gridview - 从代码后面设置列标题的 css 类?

asp.net - IIS 中的应用程序池标识和 SQL Server 的集成安全性

iis - IIS 的个人 CA 签名证书给出 "This Certificate is not valid for the selected purpose"错误

c# - Xamarin - 绑定(bind)到 ControlTemplate 中的静态类

c# - 在 StackExchange.Redis 中维护 ConnectionMultiplexer 对象的正确方法是什么?

asp.net - WebForm 项目到 MVC - 缺少上下文菜单项