microsoft-graph-apiazure-app-registration

Authentication_MissingOrMalformed when calling addKey on an App Registration


I've been attempting for days to test using this API to rotate a key. But regardless out how I do it, I always end up with "Authentication_MissingOrMalformed" and Error code 401. Is there something else I need to do?

I first created an Azure AD App Registration with the following permissions: application permissions

I then created a Self-Signed certificate and uploaded it to use as a Client Certificate, following this guide.

I then followed the guide as specified here to generate the proof.

string pfxFilePath = "certandkey.pfx";
string password = "password";
string objectId = {objectId}";

// Get signing certificate
X509Certificate2 signingCert = new X509Certificate2(pfxFilePath, password);

// audience
string aud = $"00000003-0000-0000-c000-000000000000";

// aud and iss are the only required claims.
var claims = new Dictionary<string, object>()
{
    { "aud", aud },
    { "iss", objectId }
};

// token validity should not be more than 10 minutes
var now = DateTime.UtcNow;
var securityTokenDescriptor = new SecurityTokenDescriptor
{
    Claims = claims,
    NotBefore = now,
    Expires = now.AddMinutes(10),
    SigningCredentials = new X509SigningCredentials(signingCert)
};

var handler = new JsonWebTokenHandler();
var x = handler.CreateToken(securityTokenDescriptor)

Then I generated a new self-signed certificate that I'd like to add, and export that to another file. I then attempt to call the API as follows below, but I cannot get past the exception that I see.

string tenantId = "{tenantId}";
string clientId = "{clientId}";
string newCertPath = "newcert.pfx";
X509Certificate2 newCert = new X509Certificate2(newCertPath);
var credential = new ClientCertificateCredential(tenantId, clientId, signingCert);
var graphClient = new GraphServiceClient(credential);

var requestBody = new Microsoft.Graph.Applications.Item.AddKey.AddKeyPostRequestBody
{
    KeyCredential = new KeyCredential
    {
        Type = "AsymmetricX509Cert",
        Usage = "Verify",
        Key = newCert.GetRawCertData()
    },
    PasswordCredential = null,
    Proof = x,
};
var result = await graphClient.Applications[objectId].AddKey.PostAsync(requestBody);

I would really appreciate some help in figuring out what I'm doing wrong here. I've tried this using both C# and Java, and have resulted in the same error. There should not be any permissions error, because according to the documentation, I should not need any additional permissions to do this.

permission documentation

Thanks


Solution

  • The Audience has to be "00000002-0000-0000-c000-000000000000" - The Documentation was incorrectly updated to use the client ID of the new Microsoft Graph Endpoint while this one specifically needs Azure AD Graph - it has since been fixed : https://github.com/microsoftgraph/microsoft-graph-docs-contrib/commit/03bf982d8b96b400f2d178b195fee8af9f93521b