使用托管服务帐户从 IIS 将文件写入网络驱动器

Write files to network drive from IIS using Managed Service Account

我在 Windows 2016 年在 IIS 10 中托管了一个 ASP.NET MVC 5 应用程序。我们的系统管理员已经创建了一个与此服务器绑定的托管服务帐户 (MSA),并且具有 read/write 对网络上文件夹的权限。我需要使用 MSA 从 Web 应用程序将 PDF 写入该文件夹。

目前,我只是想将一个简单的文本文件写入文件夹:

System.IO.File.WriteAllText(@"\SomeUncPath\Reports\test.txt", "sample text");

以上会产生这个错误,这是意料之中的,

System.UnauthorizedAccessException: Access to the path '\SomeUncPath\Reports\test.txt' is denied.

我关注了这个视频:https://www.youtube.com/watch?v=lBv81lwZgIo 无济于事。它只是导致站点生成 503 错误。

是否可以使用 C# 模拟来编写文件,如 this article 中所述?但是,如何模拟具有系统设置密码的 MSA?

我使用 SimpleImpersonation 尝试了以下代码:

var cred = new UserCredentials("myDomain", "someMsa$", "");
Impersonation.RunAsUser(cred, LogonType.Batch, () =>
    {
        System.IO.File.WriteAllText(@"\SomeUncPath\Reports", "sample text");
    }
);

上面抛出了这个:

System.ArgumentException: Password cannot be empty or consist solely of whitespace characters. Parameter name: password

更新 1: 服务器在系统日志中抛出以下错误:

Application pool SomePool has been disabled. Windows Process Activation Service (WAS) encountered a failure when it started a worker process to serve the application pool.

这两个警告:

Application pool SomePool has been disabled. Windows Process Activation Service (WAS) did not create a worker process to serve the application pool because the application pool identity is invalid.

The identity of application pool SomePool is invalid. The user name or password that is specified for the identity may be incorrect, or the user may not have batch logon rights. If the identity is not corrected, the application pool will be disabled when the application pool receives its first request. If batch logon rights are causing the problem, the identity in the IIS configuration store must be changed after rights have been granted before Windows Process Activation Service (WAS) can retry the logon. If the identity remains invalid after the first request for the application pool is processed, the application pool will be disabled. The data field contains the error number.

我试过 并重新启动了服务器,但问题仍然存在。

更新 2: 如果我向应用程序池提供我的凭据,应用程序加载时不会出现任何问题。仅在 MSA 上它因上述 error/warnings 而失败。 MSA 可能有什么问题?

更新 3:问题是我如何将 MSA 添加到应用程序池。我需要在用户名中包含我的域:myDomain\someMsa$。一旦我把它放进去,它就像一个魅力!

问题与将 MSA 设置为应用程序池标识时缺少域有关。添加它时,我需要将其设置为 myDomain\someMsa$ 而不是简单地 someMsa$。奇怪的是 IIS 怎么没有报错,可能是因为 MSA 帐户被认为是本地帐户和域帐户。

此外,在我们的例子中,我们不需要 MSA 的 "Log on as a batch" 权限。没有它它工作得很好。