跳至正文

Azure Custom Vision: Use managed identity or other Azure Identity

Azure Custom Vision Test Success

Refer to: 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 to other language, 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 is it work?

  1. Use “managed identity” or other identity to “login” Resource Manager Endpoint (cognitiveservices.azure.com)
  2. Got token string
  3. Use the token as key to access CustomVisionTrainingClient / CustomVisionPredictionClient.
  4. Do anything what 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.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

🌍 Language