关于powershell:使Azure身份验证无提示运行而无提示运行

Make Azure Authentication Run Silently without Password Prompt

我有一个PowerShell脚本,该脚本连接到Azure,然后下载数据。该脚本在人与人之间的交互中运行良好,但是我试图将其作为计划任务以静默方式运行。当前,每次脚本运行时,都会提示输入用户凭据。我将"始终"更改为"从不",并且似乎没有在任何时间段内存储凭据。

1
2
3
4
5
6
7
8
$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进行身份验证?


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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$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://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.security/get-credential?view=powershell-6


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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;