在 Azure Devops Pipeline for SPN 中使用 powershell 自动化 Connect-AzureAD

Automate Connect-AzureAD using powershell in Azure Devops Pipeline for SPN

我正在执行以下操作以使用 azure devops Pipeline for Powershell 任务连接到 AAD

  1. 创建了一个 SPN 并授予了图的权限
  2. 在使用下面的代码使用访问令牌进行连接时,它显示 Error Pipleline

我的代码很简单如下

    Install-Module -Name "AzureAD" -Force
   $context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
   $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
   $aadToken = [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.windows.net").AccessToken      
  
   Write-Output "Hi I'm $($context.Account.Id)"
   Write-Output "AAD Token is  $($aadToken)"
   Connect-AzureAD -TenantId $context.tenant.id -AadAccessToken $aadToken -MsAccessToken $graphToken -AccountId $context.Account.Id 
   $outputusers= get-azureaduser -Top 5
   Write-Output "The users are listed $($outputusers)"

如果我遗漏了任何细节,请告诉我。 SPN 只是一个 devops 管道,它不是 AAD 用户。因此令牌可能对身份验证无效。

要使 SPN 成为 AAD 中的用户,我需要做什么。请指教

从你的代码来看,你使用Get-AzureADUser调用Azure AD Graph,所以尝试添加Azure Active Directory Graph Directory.Read.All权限,可以解决你的问题。

对了,-MsAccessToken $graphToken命令可以省略