Access APIM API from Azure Function with Managed Identity.

Megha KG 0 Reputation points
2024-07-02T08:58:52.4133333+00:00

I have created a function app to call an API from APIM and I have added security of Auth 2.0 in the API settings. Also I have added Managed identity to the function app , and added that managed identity in APIM IAM as a API Management Service Reader role. If I call the APIM API from postman with An Auth token I'm able to access the API and retrieve the data . but While calling the API from function app with managed identity getting below UnAuthorized Error .I need to bypass the Authentication Token as it is Azure resources.I don't want to make a separate API call for Token from function App.

Error Details :
"Azure.Identity.CredentialUnavailableException: 'DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot

  • EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
  • WorkloadIdentityCredential authentication unavailable. The workload options are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/workloadidentitycredential/troubleshoot
  • ManagedIdentityCredential authentication unavailable. No response received from the managed identity endpoint.
  • Process "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\Asal\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token. 'WAM Error

Error Code: 3399614476

Error Message: SubError: consent_required V2Error: invalid_grant AADSTS65001: The user or administrator has not consented to use the application with ID '04f0c124-f2bc-4f59-8241-bf6df9866bbd' named 'Visual Studio'. Send an interactive authorization request for this user and resource. Trace ID: 9f665921-bd59-462f-a1a7-7273bbc85b00 Correlation ID: 264aac89-28b3-4328-aebf-1315b11d4078 Timestamp: 2024-07-02 08:05:31Z

Internal Error Code: 557973645

'.

  • Azure CLI authentication failed due to an unknown error. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/azclicredential/troubleshoot ERROR: AADSTS65001: The user or administrator has not consented to use the application with ID '04b07795-8ddb-461a-bbee-02f9e1bf7b46' named 'Microsoft Azure CLI'. Send an interactive authorization request for this user and resource. Trace ID: 24b4d63a-adae-45ec-a85b-3a80c1a71e00 Correlation ID: 43b9e40b-3d93-492f-88f5-4df2e38f5303 Timestamp: 2024-07-02 08:05:33Z

Interactive authentication is needed. Please run:

az login --scope api://64be891a-8b7b-4e13-b7bc-aa6623e55318/.default

  • Az.Accounts module >= 2.2.0 is not installed.
  • Azure Developer CLI could not be found.'

".

Below is my function app code:

public class Function1

{

private readonly HttpClient httpClient = new HttpClient();

private readonly ILogger _logger;

public Function1(ILoggerFactory loggerFactory)

{

    _logger = loggerFactory.CreateLogger<Function1>();

}

[Function("TestApimConnectivityWithManagedIdentity")]

public async Task<IActionResult> Run(

    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)

{

    _logger.LogInformation("Started");

    string apimEndpoint = "https://test-megha-apim.azure-api.net/store/inventory";

    try

    {

        var tokenCredential = new DefaultAzureCredential();

        var tokenRequestContext = new TokenRequestContext(new[] { "api://64be891a-8b7b-4e13-b7bc-aa6623e55318/.default" });

        _logger.LogInformation("Attempting to acquire token...");

        var accessToken = await tokenCredential.GetTokenAsync(tokenRequestContext);

        _logger.LogInformation($"Access Token: {accessToken.Token}");

        // Use the acquired token to authenticate the request to APIM

        httpClient.DefaultRequestHeaders.Authorization =

            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken.Token);

        var response = await httpClient.GetAsync(apimEndpoint);

        if (response.IsSuccessStatusCode)

        {

            return new OkObjectResult($"Successfully connected to APIM. Status Code: {response.StatusCode}");

        }

        else

        {

            return new BadRequestObjectResult($"Failed to connect to APIM. Status Code: {response.StatusCode}, Reason: {response.ReasonPhrase}");

        }

    }

    catch (Exception ex)

    {

        throw ex;

    }

    // Use DefaultAzureCredential to automatically handle the managed identity token acquisition

}

}

Is it because of any role permission issue?

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,939 questions
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,642 questions
{count} votes