使用 AzContext 令牌连接 Azure DevOps 管道中的 Microsoft Graph

问题描述 投票:0回答:2

我尝试在 PowerShell 脚本中运行

Connect-MgGraph
,但收到以下错误:

WARNING: Interactive authentication is not supported in this session, falling back to DeviceCode. Future versions will not automatically fallback to DeviceCode. 

但是管道是通过

AzContext
进行身份验证的。例如,当我调用
Connect-AzAccount
时,所有以前的 PowerShell 脚本都会成功运行。所以它不应该要求设备代码。

这是我的管道:

- task: AzurePowerShell@5
  displayName: 'Update App Registration'
  inputs:
    azureSubscription: '$(azureSubscription)'
    azurePowerShellVersion: 'LatestVersion'
    ScriptType: 'FilePath'
    ScriptPath: 'scripts/the_script.ps1'
    pwsh: true

和脚本文件:

Connect-MgGraph

$appDisplayName = "my-app"
$objectId = Get-MgApplication -Filter "displayName eq '$appDisplayName'" | Select-Object -ExpandProperty Id

如何使用

Connect-MgGraph
验证
AzContext

PS。我确保我的

azureSubscription
已分配
Application.ReadWrite.All

azure azure-powershell
2个回答
0
投票

有一个未记录的修复程序here

首先,您需要从

AzContext
获取 Microsoft Graph 访问令牌,然后将其设置为
Connect-MgGraph

因此,解决方案将像这样工作,同时保持管道任务相同:


$context = Get-AzContext
$graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
Connect-MgGraph -AccessToken $graphToken

$appDisplayName = "my-app"
$objectId = Get-MgApplication -Filter "displayName eq '$appDisplayName'" | Select-Object -ExpandProperty Id

PS:请记住,您的服务连接(在本例中为 azureSubscription 值)应至少分配有

Application.Read.All


0
投票

这解决了我的问题,只需对 Serhat 帖子进行一处更正。

Connect-MgGraph -AccessToken (ConvertTo-SecureString $graphToken -AsPlainText -Force)
© www.soinside.com 2019 - 2024. All rights reserved.