天天看點

【Azure 應用服務】Azure Function 啟用 Managed Identity後, Powershell Funciton出現 ERROR: ManagedIdentityCredential authentication failed

問題描述

編寫Powershell Function,登入到China Azure并擷取Azure AD User資訊,但是發現遇見了 [Error] ERROR: ManagedIdentityCredential authentication failed: An unexpected error occured while fetching the AAD Token. Please contact support with this provided Correlation IdStatus: 500 (Internal Server Error) 。

【Azure 應用服務】Azure Function 啟用 Managed Identity後, Powershell Funciton出現 ERROR: ManagedIdentityCredential authentication failed

問題分析

分析錯誤原因,這是因為Powershell登入時候出現錯誤,考慮到目前是登入到中國區Azure,是以使用 Connect-AzAccount 登入時,想要指定 -Environment 為 AzureChinaCloud。

而 PowerShell Function App 自動在根目錄下添加 profile.ps1 檔案, 預設檔案内容為:

# Azure Functions profile.ps1
#
# This profile.ps1 will get executed every "cold start" of your Function App.
# "cold start" occurs when:
#
# * A Function App starts up for the very first time
# * A Function App starts up after being de-allocated due to inactivity
#
# You can define helper functions, run commands, or specify environment variables
# NOTE: any variables defined that are not environment variables will get reset after the first execution

# Authenticate with Azure PowerShell using MSI.
# Remove this if you are not planning on using MSI or Azure PowerShell.
if ($env:MSI_SECRET) {
    Disable-AzContextAutosave -Scope Process | Out-Null
    Connect-AzAccount -Identity
}

# Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell.
# Enable-AzureRmAlias

# You can also define functions or aliases that can be referenced in any of your PowerShell functions.      

可見,預設的 Connect-AzAccount -Identity中并沒有指定 Environment, 是以Function在運作時,會預設連接配接到Global Azure,是以就會出現 ManagedIdentityCredential authentication failed。

PS: 如果沒有啟用Managed Identity,則$env:MSI_SECRET為False,不會執行profile.ps1中的代碼。

解決方案

在Function App頁面中,點選App Service Editor, 修改 profile.ps1 檔案。

使用

Connect-AzAccount -Environment AzureChinaCloud -Identity      

代替

Connect-AzAccount  -Identity      

操作截圖如下:

【Azure 應用服務】Azure Function 啟用 Managed Identity後, Powershell Funciton出現 ERROR: ManagedIdentityCredential authentication failed

修改後,回到Function --> Code + Test 頁面,測試問題消失。

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
Write-Host $env:MSI_SECRET
# Interact with query parameters or the body of the request.
$name = $Request.Query.Name
if (-not $name) {
    $name = $Request.Body.Name
}

$body = "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."

if ($name) {
    $body = "Hello, $name. This HTTP triggered function executed successfully."
}
#login in to azure china 
Connect-AzAccount -Environment AzureChinaCloud -identity
# get User information
Get-AzADUser -First 2 -Select 'City' -AppendSelected

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $body
})      
【Azure 應用服務】Azure Function 啟用 Managed Identity後, Powershell Funciton出現 ERROR: ManagedIdentityCredential authentication failed

注:為了是的Connect-AzAccount成功運作,需要在requirements.psd1中添加 'Az' = '7.*' ,使得Function App的執行個體安裝好Az子產品。當然,如果Function中需要其他的Powershell子產品,在這裡添加即可。

# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
    # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 
    # To use the Az module in your function app, please uncomment the line below.
    'Az' = '7.*'
}      
【Azure 應用服務】Azure Function 啟用 Managed Identity後, Powershell Funciton出現 ERROR: ManagedIdentityCredential authentication failed

附錄一:在中國區Function App中如果沒有指定Environment的其他異常有

異常一:anagedIdentityException: Exception thrown when retrieving a token using ADAL library 

Microsoft.Azure.AppService.ManagedIdentity.ManagedIdentityException: Exception thrown when retrieving a token using ADAL library --->
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException: AADSTS500011: The resource principal named 
https://management.core.windows.net/ was not found in the tenant named GSKChina. This can happen if the application has not been installed by the
administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant. Trace 
ID: cdc5ba6d-851a-45f1-a29f-20e608af0700 Correlation ID: af280748-d9f0-4d02-9ce3-ac74dffe0d23 Timestamp: 2022-04-19 09:50:50Z ---> 
System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (BadRequest). ---> 
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException: {"error":"invalid_resource","error_description":"AADSTS500011: The resource 
principal named https://management.core.windows.net/ was not found in the tenant named GSKChina. This can happen if the application has not been 
installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the 
wrong tenant.\r\n
Trace ID: cdc5ba6d-851a-45f1-a29f-20e608af0700\r\n
Correlation ID: af280748-d9f0-4d02-9ce3-ac74dffe0d23\r\n
Timestamp: 2022-04-19 09:50:50Z",
"error_codes":[500011],
"timestamp":"2022-04-19 09:50:50Z",
"trace_id":"cdc5ba6d-851a-45f1-a29f-20e608af0700",
"correlation_id":"af280748-d9f0-4d02-9ce3-ac74dffe0d23",
"error_uri":"https://login.partner.microsoftonline.cn/error?code=500011"}: 
Unknown error --- End of inner exception stack trace --- 
--- End of inner exception stack trace 
--- at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Http.AdalHttpClient.d__22`1.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Http.AdalHttpClient.d__21`1.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.d__72.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.d__69.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.d__59.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.d__57.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__33.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__58.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Azure.AppService.ManagedIdentity.Clients.AdalClient.d__2.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Azure.AppService.ManagedIdentity.Clients.AdalClient.d__0.MoveNext() 
--- End of inner exception stack trace 
--- at Microsoft.Azure.AppService.ManagedIdentity.Clients.AdalClient.d__0.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Azure.AppService.ManagedIdentity.AadProvider.d__11.MoveNext() 
--- End of stack trace from previous location where exception was thrown 
--- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at
 Microsoft.Azure.AppService.ManagedIdentity.AadProvider.GetAuthToken(String tenantId, String clientId, String secretUrl, String resource, X509Certificate2 cert, IManagedIdentityLogger logger, Boolean bypassCache, String authenticationEndpoint) at
 Microsoft.Azure.AppService.TokenService.Controllers.TokenRequestServer.GetTokenV10(ITokenServiceHttpRequest tokenRequest)
      

異常二:ManagedIdentityCredential authentication failed: An unexpected error occured while fetching the AAD Token.

2022-04-19T15:05:56.059 [Warning] WARNING: Unable to acquire token for tenant 'organizations' with error 'ManagedIdentityCredential authentication failed: 
An unexpected error occured while fetching the AAD Token. Please contact support with this provided Correlation Id
Status: 500 (Internal Server Error)Headers:Date: Tue, 19 Apr 2022 15:05:55 GMTContent-Length: 200
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot'

2022-04-19T15:05:56.847 [Error] ERROR: ManagedIdentityCredential authentication failed: 
An unexpected error occured while fetching the AAD Token. Please contact support with this provided Correlation Id
Status: 500 (Internal Server Error)Headers:Date: Tue, 19 Apr 2022 15:05:55 GMTContent-Length: 200
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshootException                   

附錄三:Connect-AzureAD -AzureEnvironmentName AzureChinaCloud 

【Azure 應用服務】Azure Function 啟用 Managed Identity後, Powershell Funciton出現 ERROR: ManagedIdentityCredential authentication failed

 Source: https://docs.microsoft.com/en-us/powershell/module/azuread/connect-azuread?view=azureadps-2.0

參考資料

Get-AzADUser : https://docs.microsoft.com/en-us/powershell/module/az.resources/get-azaduser?view=azps-7.4.0

當在複雜的環境中面臨問題,格物之道需:濁而靜之徐清,安以動之徐生。 雲中,恰是如此!

繼續閱讀