我正在尝试使用自动化帐户 Runbook 中的证书通过 Powershell (5.1) 对 Graph API 进行身份验证。
我已在受密码保护的 PFX 中创建了私钥和证书。它已上传到我的自动化帐户中的“证书”部分。我已经测试过在门户中手动上传并使用 New-AzAutomationCertificate、可导出和不可导出。
我测试过:
Import-Module Microsoft.Graph.Users
$AppId = '<app id>'
$TenantId = '<tenant id>'
$cert = Get-AzAutomationCertificate -ResourceGroupName "automation" -AutomationAccountName "aa-automation-common" -Name "cert-auth-prod-exportable"
Connect-MgGraph -Certificate $cert -TenantId $TenantId -ClientId $AppId
Get-MgUser -UserId "<user id>"
还有
Import-Module Microsoft.Graph.Users
$AppId = '<app id>'
$TenantId = '<tenant id>'
$cert = (Get-AzAutomationCertificate -ResourceGroupName "automation" -AutomationAccountName "aa-automation-common" -Name "cert-auth-prod-exportable").Thumbprint
Connect-MgGraph -CertificateThumbprint $cert -TenantId $TenantId -ClientId $AppId
Get-MgUser -UserId "<user id>"
在 Azure 中的 Runbook 中运行时,两者都会导致错误。
Get-AzAutomationCertificate : Object reference not set to an instance of an object. At line:6 char:10 + $cert = (Get-AzAutomationCertificate -ResourceGroupName "automation" ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Get-AzAutomationCertificate], NullReferenceException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Automation.Cmdlet.GetAzureAutomationCertificate
当我通过首先使用 Connect-AzAccount 登录在 VS Code 中进行本地测试时,两者都工作正常。我获取了证书信息,可以使用 Connect-MgGraph 连接并获取用户信息。
有什么线索吗?
我创建了一个受密码保护的 PFX 并将其上传到我的自动化帐户中的 “证书” 部分:
当我在我的环境中运行你的代码时,我也遇到了相同的错误,如下所示:
Import-Module Microsoft.Graph.Users
$AppId = 'appId'
$TenantId = 'tenantId'
$cert = (Get-AzAutomationCertificate -ResourceGroupName "Sri" -AutomationAccountName "testautomation" -Name "GraphCert").Thumbprint
Connect-MgGraph -CertificateThumbprint $cert -TenantId $TenantId -ClientId $AppId
Get-MgUser -UserId "xxxxxxxx"
回复:
请注意,错误发生是因为您错过了调用 Connect-AzAccount,这是
命令正常工作所必需的。Get-AzAutomationCertificate
为了解决该错误,我打开了自动化帐户的系统管理身份并向其添加了
Contributor
角色,如下所示:
当我通过系统管理身份连接到Azure来运行下面修改后的脚本时,我成功获得了包含用户详细信息的响应,如下所示:
# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process
$AzureContext = (Connect-AzAccount -Identity).context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
Import-Module Microsoft.Graph.Users
$AppId = 'appId'
$TenantId = 'tenantId'
$cert = (Get-AzAutomationCertificate -ResourceGroupName "Sri" -AutomationAccountName "testautomation" -Name "GraphCert").Thumbprint
Connect-MgGraph -CertificateThumbprint $cert -TenantId $TenantId -ClientId $AppId
Get-MgUser -UserId "xxxxxxxx"
回复:
在您的情况下,请确保在运行 Get-AzAutomationCertificate
命令之前调用
Connect-AzAccount。