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