問題描述
在中國區Azure上,使用Media Service服務,想要使用.NET的程式碼來對上傳影片建立縮圖(Thumbnail) 。
透過官網文件(https://docs.azure.cn/zh-cn/media-services/latest/samples/samples-encoding-reference#create-a-thumbnail-sprite)下載.NET示例,配置 appsettings.json 中的引數,執行卻出現(Azure.Identity.AuthenticationFailedException: 'ClientSecretCredential authentication failed: AADSTS90002: )異常。
Azure.Identity.AuthenticationFailedException: 'ClientSecretCredential authentication failed: AADSTS90002: Tenant '********-****-****-****-************' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant.
Trace ID: 99b963f7-86a5-4cde-a890-8828eff73000
Correlation ID: 62d4fa3b-92ad-4411-850c-87f562a256b3
Timestamp: 2023-05-10 07:25:55Z'
問題解答
檢視.NET專案中的原始碼,發現獲取Credential的程式碼使用的是 DefaultAzureCredential()。並且 ArmClient 物件也沒有指定Azure的執行環境。
var mediaServicesResourceId = MediaServicesAccountResource.CreateResourceIdentifier( subscriptionId: options.AZURE_SUBSCRIPTION_ID.ToString(), resourceGroupName: options.AZURE_RESOURCE_GROUP, accountName: options.AZURE_MEDIA_SERVICES_ACCOUNT_NAME); var credential = new DefaultAzureCredential(includeInteractiveCredentials: true); var armClient = new ArmClient(credential); var mediaServicesAccount = armClient.GetMediaServicesAccountResource(mediaServicesResourceId);
預設情況下,它們都是指向Global Azure,而非China Azure。
所以,解決當前問題的方法就是在DefaultAzureCredential和ArmClient方法中指定中國區Azure為執行環境。
修改這部分程式碼為為:
var mediaServicesResourceId = MediaServicesAccountResource.CreateResourceIdentifier( subscriptionId: options.AZURE_SUBSCRIPTION_ID.ToString(), resourceGroupName: options.AZURE_RESOURCE_GROUP, accountName: options.AZURE_MEDIA_SERVICES_ACCOUNT_NAME); DefaultAzureCredentialOptions dacOptions = new DefaultAzureCredentialOptions() { AuthorityHost = AzureAuthorityHosts.AzureChina }; var credential = new DefaultAzureCredential(dacOptions); ArmClientOptions armOptions = new ArmClientOptions() { Environment = ArmEnvironment.AzureChina}; var armClient = new ArmClient(credential, options.AZURE_SUBSCRIPTION_ID.ToString(), armOptions); var mediaServicesAccount = armClient.GetMediaServicesAccountResource(mediaServicesResourceId);
注意:使用 DefaultAzureCredential 認證,需要設定以下的環境變數
- AZURE_CLIENT_ID
- AZURE_TENANT_ID
- AZURE_CLIENT_SECRET
關於DefaultAzureCredential方法獲取認證引數的順序,如下圖所示:
參考資料
DefaultAzureCredential : https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#defaultazurecredential