Azure App Config HMAC 身份验证 returns 未授权错误

Azure App Config HMAC authentication returns Unauthorized error

我正在学习 this 教程,了解如何使用 HMAC 身份验证对 Azure App Config 进行 REST 调用以添加键值条目。 JS 和 c# 版本都不起作用——我最终得到一个 401 Unauthorized error saying

HMAC-SHA256 error="invalid_token", error_description="Invalid Signature"

我的 C# 实现的调用代码是:

var credential = "<my app config id>";
var secret = Encoding.ASCII.GetBytes(Base64Encode("<my app config secret>"));

UserQuery.MsgRouterConfigValue body = new MsgRouterConfigValue();
var key = "asd1";
body.clientId = Guid.NewGuid();
body.serviceUrl = new Uri("https://someuri");

using (var client = new HttpClient())
{
    var request = new HttpRequestMessage()
    {
        RequestUri = new Uri($"<my app config url>/kv/{key}?label=dev&api-version=1.0"),
        Method = HttpMethod.Put,
        Content = new StringContent(JsonSerializer.Serialize(body)) 
    };
    
    Sign(request,credential, secret);

    var resp = await client.SendAsync(request);
    
}

public static string Base64Encode(string plainText)
{
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    return System.Convert.ToBase64String(plainTextBytes);
}

关于我用于凭据和机密的值,它们来自应用程序配置门户:

谁能告诉我为什么会出现 401 错误?

编辑: 所以这个错误归结为:

Reason: The Signature provided doesn't match what the server expects.

Solution: Make sure the String-To-Sign is correct. Make sure the Secret is correct and properly used (base64 decoded prior to using).

因此,就 'Make sure the String-To-Sign is correct' 而言,我使用了与示例中提供的代码相同的代码,这使得秘密是错误的,但这与应用程序配置门户中定义的值相同。

可能是 TLS 要求

尝试:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

在创建客户端之前。

@auburg secret 在使用前必须经过 base64 解码。您共享的代码不执行此操作。你可能想打电话给 Convert.FromBase64String.

我从 Azure 收到了同样的消息,尽管我的凭据有效。原来,我的本地 Date/Time 设置 不正确(做了一些时钟更改,弄乱了当前时间)。将 date/time 固定为实际当前时间后,它恢复正常。

发生这种情况是因为 Azure 发布了一个短期令牌并将您的 UTC 时间与他们的进行比较以确保令牌有效。可能并非所有“无效令牌”问题都如此,但绝对值得检查。