Azure Custom Vision: Use managed identity or other Azure Identity
This article was translated by AI (LLM). There may be errors or inaccuracies. For the original content, please refer to the original version.
Reference: Custom Vision: Azure role-based access control, Custom Vision: azure.identity credentials aren’t supported
C# Code
First of all, the C# Code. You can also translate it to other languages like Python.
using System;
using Azure.Core;
using Azure.Identity;
using Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training;
using Microsoft.Rest;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
string customVisionEndpoint = "https://<your_project_name>.cognitiveservices.azure.com/";
try
{
// If you are using a managed identity, you can use the following code to get the token
//var miClientId = "<your_managed_identity_client_id>";
//var tokenCredential = new ManagedIdentityCredential(miClientId);
// If you are using DefaultAzureCredential for local development, you can use the following code to get the token
var tokenCredential = new DefaultAzureCredential();
var mercuryResourceUri = "https://cognitiveservices.azure.com";
var tokenRequestContext = new TokenRequestContext(new[] { $"{mercuryResourceUri}/.default" });
var token = tokenCredential.GetToken(tokenRequestContext).Token;
// Create a CustomVisionTrainingClient
var trainingClient = new CustomVisionTrainingClient(new TokenCredentials(token))
{
Endpoint = customVisionEndpoint,
};
Console.WriteLine("CustomVisionTrainingClient Instance Created");
var projects = trainingClient.GetProjects();
foreach (var project in projects)
{
Console.WriteLine($"Project Name: {project.Name}, Project ID: {project.Id}");
}
}
catch (Exception ex)
{
Console.WriteLine($"exception: {ex.Message}");
}
}
}
}
But, why does it work?
- Use “managed identity” or other identity to “login” to Resource Manager Endpoint (cognitiveservices.azure.com)
- Obtain token string
- Use the token as a key to access CustomVisionTrainingClient / CustomVisionPredictionClient
- Do anything you want!
Setting in Azure portal
Follow Custom Vision: Azure role-based access control, add a role for your Managed Identity or a user like yourself.