使 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 进行身份验证?

你可以从这个线程中检查波格丹·加夫里尔分享的脚本。

#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;

我能够弄清楚这一点。 我提供的初始身份验证代码使用特定于 Azure 的弹出窗口来获取凭据。 使用以下链接 [1] 我将代码转换为 PowerShell Get-Credential 方法。 从那里,我使用此链接 [2](示例 7)中的信息将 Get-Credential 方法配置为从纯文本而不是弹出窗口中提取。

现在纯文本密码并不理想,但对于我们的需求来说,它已经足够好了。

$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
$User = "<USERNAMEHERE>"
$PWord = ConvertTo-SecureString -String "<PASSWORDHERE>" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName,$credential.Password
$authResult = $authContext.AcquireToken($MSGraphURI, $clientId, $AADCredential)
$token = $authResult.AccessToken

[1] https://blogs.technet.microsoft.com/cloudlojik/2017/09/05/using-powershell-to-connect-to-microsoft-graph-api/

[2] https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/get-credential?view=powershell-6

相关内容

最新更新