使Azure身份验证静默运行而不会出现密码提示

时间:2019-01-24 00:18:18

标签: azure powershell microsoft-graph

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

$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进行静默身份验证?

2 个答案:

答案 0 :(得分:0)

您可以检查this thread中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;

答案 1 :(得分:0)

我能够弄清楚这一点。我提供的初始身份验证代码使用特定于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://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/get-credential?view=powershell-6