gpt4 book ai didi

c# - Azure Web App System.UnauthorizedAccessException 一旦部署到 Azure 就无法访问本地网络上的共享文件夹

转载 作者:行者123 更新时间:2023-12-03 04:19:26 26 4
gpt4 key购买 nike

我们有一个混合 Azure/本地网络。我可以从 Azure 网络上的 VM 访问共享驱动器\192.168.74.10\Shared\LIS\For Upload\Reports(在本地网络上)。如果我将地址粘贴到文件资源管理器中,它会要求输入用户名和密码。一旦给出,我就可以从虚拟机访问报告文件夹。

当我从通过 VPN 连接到网络的计算机上运行 Visual Studio 中的 Web 应用程序时,我能够访问 192.168.74.10 上的共享驱动器。该计算机不是 AD 的一部分,只是通过 VPN 接入网络。将 Web 应用程序部署到 azure 云后,我在尝试访问该文件夹时收到 System.UnauthorizedAccessException。

我从另一篇文章复制了 WrappedImpersonationContext 代码。添加 WrappedImpersonationContext 允许我的 Web 应用程序从通过 VPN 连接到网络的计算机访问该文件夹。

WrappedImpersonationContext 代码:

 public sealed class WrappedImpersonationContext
{
public enum LogonType : int
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
Unlock = 7,
NetworkClearText = 8,
NewCredentials = 9
}

public enum LogonProvider : int
{
Default = 0, // LOGON32_PROVIDER_DEFAULT
WinNT35 = 1,
WinNT40 = 2, // Use the NTLM logon provider.
WinNT50 = 3 // Use the negotiate logon provider.
}

[DllImport("advapi32.dll", EntryPoint = "LogonUserW", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain,
String lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);

[DllImport("kernel32.dll")]
public extern static bool CloseHandle(IntPtr handle);

private string _domain, _password, _username;
private IntPtr _token;
private WindowsImpersonationContext _context;

private bool IsInContext
{
get { return _context != null; }
}

public WrappedImpersonationContext(string domain, string username, string password)
{
_domain = String.IsNullOrEmpty(domain) ? "." : domain;
_username = username;
_password = password;
}

// Changes the Windows identity of this thread. Make sure to always call Leave() at the end.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void Enter()
{
if (IsInContext)
return;

_token = IntPtr.Zero;
bool logonSuccessfull = LogonUser(_username, _domain, _password, LogonType.NewCredentials, LogonProvider.WinNT50, ref _token);
if (!logonSuccessfull)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
WindowsIdentity identity = new WindowsIdentity(_token);
_context = identity.Impersonate();

Debug.WriteLine(WindowsIdentity.GetCurrent().Name);
}

[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void Leave()
{
if (!IsInContext)
return;

_context.Undo();

if (_token != IntPtr.Zero)
{
CloseHandle(_token);
}
_context = null;
}
}

上传文件的代码:

public ActionResult UploadDirectoryEncrypted()
{

int fileType = 2;

StorageCredentials creds = new StorageCredentials(
ConfigurationManager.AppSettings["accountName"],
ConfigurationManager.AppSettings["accountKey"]);

CloudStorageAccount storageAccount = new CloudStorageAccount(creds, useHttps: true);

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

var impersonationContext = new WrappedImpersonationContext(ConfigurationManager.AppSettings["ServerDomain"], ConfigurationManager.AppSettings["ServerUser"], ConfigurationManager.AppSettings["ServerPassword"]);
impersonationContext.Enter();

string sourceDirectory = @"\\192.168.74.10\Shared\LIS\For Upload\Reports\";

var folder = new DirectoryInfo(sourceDirectory);
var files = folder.GetFiles();
foreach (var fileInfo in files)
{
string blobName = fileInfo.Name;
string blobFilePath = sourceDirectory + blobName;
double accession_number = Convert.ToDouble(blobName.Substring(0, blobName.Length - 3));

CloudBlobContainer container = GetContainer(blobClient, Convert.ToInt32(fileType));

KeyVaultKeyResolver cloudResolver = new KeyVaultKeyResolver(GetToken);

var rsa = cloudResolver.ResolveKeyAsync(ConfigurationManager.AppSettings["keyId"], CancellationToken.None).GetAwaiter().GetResult();

BlobEncryptionPolicy policy = new BlobEncryptionPolicy(rsa, null);
BlobRequestOptions options = new BlobRequestOptions() { EncryptionPolicy = policy };

CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

using (var stream = System.IO.File.OpenRead(blobFilePath))
blob.UploadFromStream(stream, stream.Length, null, options, null);

System.IO.File.Delete(blobFilePath);
}
impersonationContext.Leave();
return RedirectToAction("Index", "User");
}

我已完全控制网络服务、IUSR 和 IIS_IUSRS,但仍然收到以下访问被拒绝错误。

Server Error in '/' Application.
Access to the path '\\192.168.74.10\Shared\LIS\For Upload\Reports' is
denied.

Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access to the path
'\\192.168.74.10\Shared\LIS\For Upload\Reports' is denied.

ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request identity.
ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or
Network Service on IIS 6 and IIS 7, and the configured application pool
identity on IIS 7.5) that is used if the application is not impersonating.
If the application is impersonating via <identity impersonate="true"/>, the
identity will be the anonymous user (typically IUSR_MACHINENAME) or the
authenticated request user.

To grant ASP.NET access to a file, right-click the file in File Explorer,
choose "Properties" and select the Security tab. Click "Add" to add the
appropriate user or group. Highlight the ASP.NET account, and check the
boxes for the desired access.

如何才能访问本地网络上的文件夹?

最佳答案

建议将文件存储在 Azure 存储中,而不是在任何虚拟路径或目录下,因为这可能会影响/重新启动本地网络 (VS) 上的站点。

关于c# - Azure Web App System.UnauthorizedAccessException 一旦部署到 Azure 就无法访问本地网络上的共享文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50479119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com