繁体   English   中英

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

[英]Azure Web App System.UnauthorizedAccessException once deployed to Azure can't access shared folder on local network

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

从连接到网络的计算机从Visual Studio运行Web应用程序时,我可以访问192.168.74.10上的共享驱动器。 该计算机不是AD的一部分,只是通过VPN接入网络。 将Web应用程序部署到蔚蓝云后,尝试访问该文件夹时出现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)上的站点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM