首页 > 解决方案 > 使 Azure 身份验证在没有密码提示的情况下静默运行

问题描述

我有一个连接到 Azure 的 PowerShell 脚本,然后下载数据。该脚本在人机交互中运行良好,但我试图将其作为计划任务静默运行。目前,每次脚本运行时,它都会提示输入用户凭据。我将“始终”更改为“从不”,它似乎不会在任何时间长度内存储凭据。

$clientId = "<CLIENTIDHERE>" # PowerShell clientId
$redirectUri = "<REDIRECTURIHERE>"
$MSGraphURI = "https://graph.microsoft.com"

$authority = "https://login.microsoftonline.com/$tenantId"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$authResult = $authContext.AcquireToken($MSGraphURI, $clientId, $redirectUri, "Always")
$token = $authResult.AccessToken

理想情况下,凭据将根据计划任务中运行的凭据传递。如果这不是一个选项,至少我希望将用户名和密码放在脚本中,并让脚本发送这些凭据以进行身份​​验证。如何以静默方式向 Azure 进行身份验证?

标签: azurepowershellmicrosoft-graph-api

解决方案


您可以从这个线程检查 Bogdan Gavril 共享的脚本。

#Require -Version 5.0
using namespace Microsoft.IdentityModel.Clients.ActiveDirectory

$adalDll = [Reflection.Assembly]::LoadFile("<path_to>\Microsoft.IdentityModel.Clients.ActiveDirectory.dll")

$ADAuthorityURL = "https://login.windows.net/common/oauth2/authorize/"
$resourceURL = "https://analysis.windows.net/powerbi/api"
$AADuserName = "foo"
$AADpassword = "bar"

Write-Host "Retrieving the AAD Credentials...";

$credential = New-Object UserPasswordCredential($AADuserName, $AADpassword);
$authenticationContext = New-Object AuthenticationContext($ADAuthorityURL);
$authenticationResult = [AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authenticationContext, $resourceURL, $AADClientID, $credential).Result;

$ResultAAD = $authenticationResult.AccessToken;

推荐阅读