【Azure 应用服务】Azure Function 启用 Managed Identity后, Powershell Funciton出现 ERROR: ManagedIdentityCred...

问题描述

编写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) 。


image.png

问题分析

分析错误原因,这是因为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

操作截图如下:


image.png

修改后,回到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 })
image.png

注:为了是的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.*'
}
image.png

附录一:在中国区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      

参考资料

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

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

标签: App Service, Azure Developer, Azure Function, ManagedIdentityCredential authentication failed, Connect-AzAccount-identity, -Environment AzureChinaCloud

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 224,289评论 6 522
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 95,968评论 3 402
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 171,336评论 0 366
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 60,718评论 1 300
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 69,734评论 6 399
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,240评论 1 314
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,631评论 3 428
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 40,599评论 0 279
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 47,139评论 1 324
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,166评论 3 345
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,286评论 1 354
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,917评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,604评论 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,075评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,205评论 1 275
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,814评论 3 381
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,351评论 2 365

推荐阅读更多精彩内容