You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Azure Function跨订阅认证访问Azure Windows虚拟机文件?

Azure Function访问跨订阅Windows虚拟机文件共享的认证解决方案

问题定位

你遇到的"Access to the path is denied"错误,大概率是三个原因:LogonType选择错误、文件共享权限配置不足、代码路径语法错误。结合你用SimpleImpersonation的场景,逐个解决:

核心解决步骤

1. 确认文件共享的双重权限

虚拟机上的andrewd账号必须同时拥有:

  • 共享权限:在文件共享的属性设置中,给andrewd分配至少读取权限
  • NTFS权限:右键目标文件/文件夹→属性→安全,给andrewd分配读取 & 执行权限

2. 正确选择LogonType

针对网络文件共享场景,必须用LogonType.NewCredentials——这个类型专门用于在不加载用户本地配置文件的情况下,使用新凭证访问网络资源,完美适配Azure Function这类服务运行环境。其他类型(比如Interactive)会尝试加载用户本地配置,在服务环境下容易失败。

3. 修正代码错误

你的代码里有两个明显问题:

  • 文件路径末尾多了一个},导致路径无效
  • LogonType未指定正确值

修正后的代码:

try
{
    var credentials = new UserCredentials("virtualmachinedomain.com.au", "andrewd", "passwordhere");
    // 使用NewCredentials类型完成登录
    using SafeAccessTokenHandle userHandle = credentials.LogonUser(LogonType.NewCredentials);  

    WindowsIdentity.RunImpersonated(userHandle, () =>
    {
        // 修正路径,去掉多余的}
        string filePath = @"\\fileserver.com.au\WordDocToAccessOnFileShare.doc";
        logger.LogInformation($"当前模拟用户:{WindowsIdentity.GetCurrent().Name}"); // 验证身份是否正确切换
        using FileStream fileStream = new FileStream(filePath, FileMode.Open);
        if (fileStream != null && fileStream.Length > 0)
        {
            messageReturnedAsPartOfOkReesult += "Result: Able to reference file";
            logger.LogInformation("able to reference file");
        }
    });
}
catch (Exception ex)
{
    messageReturnedAsPartOfOkReesult += $"Result: Unable to reference file. Exception: {ex.Message}";
    logger.LogError($"Unable to reach file {ex.Message}");
    if (ex.InnerException != null)
    {
        logger.LogError($"Inner exception {ex.InnerException.Message}");
    }
}

额外验证项

  • 网络连通性:虽然配置了VNet对等,但要确认Azure Function能访问虚拟机的SMB端口(445),虚拟机本地防火墙需允许SMB入站请求
  • 域名解析:fileserver.com.au要能被Azure Function解析到虚拟机的私有IP,建议用Azure私有DNS区域配置内部域名解析
  • Azure Function计划:确保使用专用计划或弹性计划,消耗计划的VNet集成对SMB访问有诸多限制,容易引发权限类问题

内容的提问来源于stack exchange,提问作者Andrew Duffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:15:44