samraj
samraj

Reputation: 39

Calling Azure Translator Service from web app with Managed Identity

I am new to Azure. I am calling azure translation service from web app. I want to use managed identity and so as far I tried below approach. Do you think this is the correct way. Or do I need to do anything in web app identity as well ? enter image description here

  1. Enabled managed identity in Translation Service
  2. Grant Access to Translator Service In Azure Translator => Access control (IAM) => Add role assignment => Contributor to created managed identity.
  3. Code Integration in web app

// Initialize the Azure Translator client

var credential = new ChainedTokenCredential(new ManagedIdentityCredential(), new AzureCliCredential()); var translatorClient = new TranslationClient(new Uri(endpoint), credential);

Upvotes: 1

Views: 1108

Answers (1)

SiddheshDesai
SiddheshDesai

Reputation: 8195

I agree with Nicolas R. Whenever you want to connect Web app to any resource, Its better to connect Web app managed Identity to the Translator service and then access the Translation API via your Azure Web app middleware or code.

Refer this MS Q & A answer flow to use Cognitive service in Angular app. Use the same steps for your C# .net Web app, by Sedat SALMAN.

Enable managed Identity for your Web app like below:-

enter image description here

Grant this managed identity access to Translator Service like below:-

enter image description here

Now Integrate this C# Translator service code in your web app middleware to return the Translation API. You can also call this Rest API from your Web app. Refer below:-

Add one class TranslationService.cs and add the below code with correct API Key, Location and Endpoint of Translator service like below:-

TranslationService.cs without managed Identity

enter image description here

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class TranslationService
{
    private static readonly string key = "xxxxxxc051dfbc";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    
    private static readonly string location = "australiaeast";

    public static async Task TranslateText(Stream body)
    {
       
        string route = "/translate?api-version=3.0&from=en&to=fr&to=zu";
        string textToTranslate = "I would really like to drive your car around the block a few times!";
        object[] requestBody1 = new object[] { new { Text = textToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
           
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            
            HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
           
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

TranslationService.cs with managed Identity You can use any one of the codes depending upon your use case:-

using Azure.Identity;
using Azure.Core;
using Azure.AI.Translation.Document;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

public class TranslationService
{
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    public static async Task<string> TranslateText()
    {
        string textToTranslate = "I would really like to drive your car around the block a few times!";

        var tokenCredential = new ManagedIdentityCredential();
        var translationClient = new DocumentTranslationClient(new Uri(endpoint), tokenCredential);

        var options = new TranslationRequestOptions { FromLanguage = "en", ToLanguages = { "fr", "zu" } };
        var documents = new List<DocumentTranslationInput>
        {
            new DocumentTranslationInput("1", textToTranslate),
        };

        var operation = await translationClient.StartTranslationAsync(documents, options);

        // Wait for the translation operation to complete
        await operation.WaitForCompletionAsync();

        if (operation.GetRawResponse().Status == 200)
        {
            var result = operation.GetValues().FirstOrDefault()?.Translations.FirstOrDefault()?.Text;
            return result ?? "Translation failed.";
        }
        else
        {
            return "Translation failed.";
        }
    }
}

Create one Razor page in Shared folder in Pages of Asp.net web app:-

Translation.cshtml:-

@page
@model TranslationModel

<button id="translateButton" class="btn btn-primary">Translate</button>

@section scripts {
    <script>
        document.getElementById('translateButton').addEventListener('click', function () {
            // Call the translation function when the button is clicked
            fetchTranslation();
        });

        function fetchTranslation() {
            fetch('/Translation/Translate')
                .then(response => response.text())
                .then(result => {
                    console.log(result);
                    // You can display the translation result as needed on the page.
                })
                .catch(error => {
                    console.error('Translation error:', error);
                });
        }
    </script>
}

Translation.cshtml.cs:-

using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Threading.Tasks;

public class TranslationModel : PageModel
{
    public async Task OnGet()
    {
        // This is the default handler when the page is requested. You can leave it empty or add any necessary initialization code.
    }
}

Updated Program.cs like below:-


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

// Map your translation route
app.MapGet("/Translation/Translate", async context =>
{
    // Call the TranslateText method from the TranslationService
    await TranslationService.TranslateText(context.Response.Body);
});

app.MapRazorPages();

app.Run();

Apply same logic for the managed Identity Web app.

Output:-

enter image description here

Upvotes: 0

Related Questions