如何在启用authentication情况下调试Azure Function (Azure Portal side)

发布时间 2023-05-29 11:06:35作者: 弥赛亚之剑

Azure Function是一个很好用的工具,我经常把在Power Automate里实现起来麻烦的逻辑放在Azure Function里。

如果你创建一个新的azure function,它默认是没有启用任何authentication的(可以匿名访问),这个时候你可以用系统自带的“Code/Test”界面随便调试。

 

为了安全起见,我们一般要启用authentication (详情见https://learn.microsoft.com/en-us/azure/app-service/overview-authentication-authorization )来保护这个api。 微软提供了一键enable的方式,会创建一个对应的app registration。

 启用完了之后你就没法正常用这个调试界面了。你怎么改azure function的trigger的authentication level都没用。

你必须在这个test request的header里加authentication的token, token的值前面要加“Bearer ”(见下图)

 

获取这个token有好几种方法,我喜欢用MSAL这个powershell module。你可以用如下命令装这个module

Install-Module MSAL.PS

  

它可以根据app registration的client id, client secret去获取token

你要去azure function相应的app registration去拿对应的值

 具体的app registration页面

 

然后用Get-MsalToken这个powershell命令去获取token

$result = Get-MsalToken -ClientId {Client Id} -ClientSecret (ConvertTo-SecureString {Client Secret} -AsPlainText -Force) -TenantId {tenant id} -Scope {scope}

 

再把Access token复制到Azure function test界面的authentication header里(注意这个token一个小时后会过期)

 然后就可以用test功能了