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

移动端调用带Function Key的Azure Function接口返回401未授权

Azure Function 调用返回401未授权问题

错误信息

StatusCode: 401, ReasonPhrase: 'Unauthorized'

调用代码

let postToAsync (baseAddress:string) (resource:string) (payload:Object) =
async {

    let tokenSource = new CancellationTokenSource(TimeSpan(0,0,30));
    let token = tokenSource.Token;
    
    try
        let tokens      = resource.Split("?code=")
        let functionKey = tokens.[1]

        use client = httpClient baseAddress
        client.DefaultRequestHeaders.Add("x-functions-key", functionKey)
        client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue("application/json"))

        let  json     = JsonConvert.SerializeObject(payload)
        let  content  = new StringContent(json, Encoding.UTF8, "application/json")
        let! response = client.PostAsync(resource.Replace($"?code={functionKey}",""), content, token) |> Async.AwaitTask

        Debug.WriteLine $"\n\n{baseAddress}{resource}\nSuccess: {response.IsSuccessStatusCode}\n\n" 

        return response

    with ex -> ...
} |> Async.StartAsTask

关键信息

  • Azure Function的AuthorizationLevel设置为Function
  • Visual Studio手动发布的Function可正常调用,但Pulumi部署的Function返回Unauthorized响应,推测原因是Pulumi强制为每个Function App添加了访问策略

版本信息

<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>

问题线索

推测oauth2/v2.0相关机制可能是问题诱因,但暂未找到解决方法

连通性验证

已通过日志流确认请求URL正确:
请求URL正确的日志截图

访问控制差异

手动创建的Function App无额外访问策略,而Pulumi生成的Function App会通过以下代码添加Key Vault访问策略:

public static class AccessPolicies
{
    public static void Build(string policyName, string functionName, Dictionary<string, CustomResource> registry)
    {
        var resourceGroup = registry[nameof(ResourceGroup)] as ResourceGroup;
        var keyVault      = registry[nameof(KeyVault)]      as KeyVault;
        var functionApp   = registry[functionName]   as FunctionApp;

        var result = new AccessPolicy(policyName, new AccessPolicyArgs {

            KeyVaultId = keyVault.Id,
            TenantId   = TenantId.Value,
            ObjectId   = functionApp.Identity.Apply(v => v.PrincipalId ?? "11111111-1111-1111-1111-111111111111"),
            KeyPermissions    = new[] { "Get", },
            SecretPermissions = new[] { "Get", }, 
        });

        registry.Add($"{policyName}-{functionName}", result);
    }
}

内容的提问来源于stack exchange,提问作者Scott Nimrod

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:15:38