Search code examples
c#.net-corehmacazure-app-configuration

Azure App Config HMAC authentication returns Unauthorized error


I'm following this tutorial on making a REST call to Azure App Config to add a key-value entry using HMAC authentication. Both the JS and c# versions don't work - i end up with a 401 Unauthorized error saying

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

My calling code for the C# implementation is:

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);
}

With regards to the values i'm using for credential and secret, they are from the portal for app config:

enter image description here

Can anyone advise why i'm getting a 401 error ?

EDIT: So this error is down to:

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).

So in terms of the 'Make sure the String-To-Sign is correct' i'm using the same code as provided in the example, which leaves the secret being wrong but this is the same value as defined in the portal for the app config.


Solution

  • @auburg the secret must be base64 decoded before using. The code you shared doesn't do it. You may want to call Convert.FromBase64String.