Azure function app : ManagedIdentityCredential authentication failed.

Sripad Subhajit Sahu 1 Reputation point
2022-08-03T17:37:29.327+00:00

While updating the digitaltwin instance using the function app I am getting error :

ManagedIdentityCredential authentication failed: Service request failed.Status: 400 (Bad Request)Content:Headers:Date: Wed, 03 Aug 2022 17:24:18 GMTServer: KestrelTransfer-Encoding: chunkedX-CORRELATION-ID: REDACTEDContent-Type: application/json; charset=utf-8See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot

A simple function app code :

using System;  
using Microsoft.Azure.WebJobs;  
using Microsoft.Azure.WebJobs.Host;  
using Microsoft.Azure.EventGrid.Models;  
using Microsoft.Azure.WebJobs.Extensions.EventGrid;  
using Microsoft.Extensions.Logging;  
using Azure.DigitalTwins.Core;  
using Azure.Identity;  
using System.Net.Http;  
using Azure.Core.Pipeline;  
using Newtonsoft.Json.Linq;  
using Newtonsoft.Json;  
using Azure;  
  
namespace factorytwiningestfunction  
{  
    public static class Function1  
    {  
        private static readonly string adtInstanceUrl = Environment.GetEnvironmentVariable("ADT_SERVICE_URL");  
        private static readonly HttpClient singletonHttpClientInstance = new HttpClient();  
  
        [FunctionName("IOTHubtoTwins")]  
        public async static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)  
        {  
            if (adtInstanceUrl == null) log.LogError("Application setting \"ADT_SERVICE_URL\" not set");  
            try  
            {  
                var cred = new ManagedIdentityCredential("https://digitaltwins.azure.net");  
  
                var client = new DigitalTwinsClient(  
                new Uri(adtInstanceUrl),  
                cred,  
                new DigitalTwinsClientOptions  
                {  
                    Transport = new HttpClientTransport(singletonHttpClientInstance)  
                });  
  
                log.LogInformation($"ADT service client connection created.");  
  
                if (eventGridEvent != null && eventGridEvent.Data != null)  
                {  
                    log.LogInformation(eventGridEvent.Data.ToString());  
  
                    // convert the message into a json object  
                    JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());  
  
                    log.LogInformation($"object is :{deviceMessage.ToString()}");  
  
                    // get our device id, temp and humidity from the object  
                    string deviceId = (string)deviceMessage["systemProperties"]["iothub-connection-device-id"];  
                    //var temperature = deviceMessage["body"]["Temperature"];  
                    //var humidity = deviceMessage["body"]["Humidity"];  
                    var distance = deviceMessage["body"]["Distance"];  
  
                    //log the temperature and humidity  
                    log.LogInformation($"Device:{deviceId} distance is:{distance}");  
  
                    // Update twin with temperature and humidity fro our raspberry pi>  
                    var updateTwinData = new JsonPatchDocument();  
                    updateTwinData.AppendReplace("/Distance", distance.Value<int>());  
                    await client.UpdateDigitalTwinAsync(deviceId, updateTwinData);  
                }  
            }  
  
            catch (Exception ex)  
            {  
                log.LogError($"Error in ingest function: {ex.Message}");  
            }  
  
        }  
    }  
}  
  

Please do advise what am I doing wrong?

Thank you.

Azure Digital Twins
Azure Digital Twins
An Azure platform that is used to create digital representations of real-world things, places, business processes, and people.
220 questions
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,321 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. mainak chakraborty 6 Reputation points
    2022-08-06T21:48:42.12+00:00

    Instead of this:

                 var cred = new ManagedIdentityCredential("https://digitaltwins.azure.net");  
      
                 var client = new DigitalTwinsClient(  
                 new Uri(adtInstanceUrl),  
                 cred,  
                 new DigitalTwinsClientOptions  
                 {  
                     Transport = new HttpClientTransport(singletonHttpClientInstance)  
                 });  
    

    Please try:
    //NEW CODE FOR IDENTITY
    var cred = new DefaultAzureCredential();
    var client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred);

    Worked for me.

    1 person found this answer helpful.
    0 comments No comments