Retrieving an access token with managed credential

Jinjing Arima 20 Reputation points Microsoft Employee
2024-07-22T20:21:47.7+00:00

I've been working on letting my web app to submit text translate request to my azure translator service with managed identity.
Following the translator v3.0 document: https://learn.microsoft.com/en-us/azure/ai-services/translator/reference/v3-0-reference
I see there is a section : Authentication with Microsoft Entra ID but it does not explain how I can retrieve an access token using managed identity. After some research, I think I will need to call ManagedIdentityCredential.GetToken but that requires a list of scopes, and I could not find a translator service documentation of what scope is needed for access token retrieval. Any help will be appreciated.

Azure Translator
Azure Translator
An Azure service to easily conduct machine translation with a simple REST API call.
408 questions
0 comments No comments
{count} votes

Accepted answer
  1. hossein jalilian 8,080 Reputation points
    2024-07-22T20:38:35.1166667+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    Enable managed identity for your web app in Azure. grant the managed identity access to your Azure Translator resource. use the appropriate SDK to retrieve an access token using the managed identity and use the token to authenticate your requests to the Translator service.

    Here's an example of how you might retrieve and use the token in C#:

    using Azure.Identity;
    using Azure.Core;
    using System.Net.Http;
    using System.Text;
    using System.Text.Json;
    
    var credential = new ManagedIdentityCredential();
    
    var scope = "https://cognitiveservices.azure.com/.default";
    var accessToken = await credential.GetTokenAsync(new TokenRequestContext(new[] { scope }));
    
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Region", "<your-region>");
    
        var content = new StringContent("[{'Text':'Hello, world!'}]", Encoding.UTF8, "application/json");
        
        var response = await client.PostAsync("https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es", content);
        
        var responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseContent);
    }
    
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.