如何使用PowerShell使用单个用户名/密码提示对AzureRM和AzureAD进行身份验证

时间:2018-02-16 01:50:27

标签: powershell azure authentication azure-active-directory

我有几个需要连接到AAD和ARM的脚本,所以我使用了这段代码: $creds= Get-Credential Connect-AzureRmAccount -Credential $creds Connect-AzureAD -Credential $creds (我实际上用Get-AzureRmSubscription包装了代码片段,如果失败则只提示凭据。

但是我的组织已经实施了MFA,我知道我不能再使用-Credential参数了。所以我的连接片段现在是: Connect-AzureRmAccount Connect-AzureAD (仍然在测试条件下包裹)。

但是,我一直试图解决的问题是我可以以某种方式使用第一个connect cmdlet中的身份验证“令牌”并将其传递给第二个connect cmdlet吗? /强>

作为解决方法,我可以

  1. 使用服务主体运行我的脚本
  2. 使用不带MFA的帐户,然后返回将我的凭据存储在PSCredential对象中
  3. 但我认为这不会通过首先启用MFA的安全团队! :)

    这对新的PS会话来说只是一个问题。一旦我通过身份验证,连接测试就会通过,我不会再次收到提示,但只是觉得应该只需要输入我的用户名,密码和MFA质询一次。毕竟,我只需要登录Azure门户并访问AAD和ARM。

2 个答案:

答案 0 :(得分:4)

最新版本的AzureRM模块(v5.3.0)包含新的cmdlet *-AzureRmAd*,它们与*-AzureAd* cmdlet的作用相同。

因此,我需要更新我的脚本以使用这些新的cmdlet。然后我不需要连接到AAD,只需要连接一次到ARM。

答案 1 :(得分:1)

根据您的方案,我建议您创建一个服务主体来登录Azure Power Shell和Azure AD Power Shell。

您可以查看official document

# Create the self signed cert
$currentDate = Get-Date
$endDate  = $currentDate.AddYears(1)
$notAfter  = $endDate.AddYears(1)
$pwd  = "<password>"
$thumb = (New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my -DnsName com.foo.bar -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
$pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
Export-PfxCertificate -cert "cert:\localmachine\my\$thumb" -FilePath c:\temp\examplecert.pfx -Password $pwd

# Load the certificate
$cert  = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("C:\temp\examplecert.pfx", $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())


# Create the Azure Active Directory Application
$application = New-AzureADApplication -DisplayName "test123" -IdentifierUris "https://test123"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "Test123" -StartDate $currentDate -EndDate $endDate -Type AsymmetricX509Cert -Usage Verify -Value $keyValue

# Create the Service Principal and connect it to the Application
$sp = New-AzureADServicePrincipal -AppId $application.AppId

# Give the Service Principal Reader access to the current tenant (Get-AzureADDirectoryRole)
Add-AzureADDirectoryRoleMember -ObjectId 5997d714-c3b5-4d5b-9973-ec2f38fd49d5 -RefObjectId $sp.ObjectId

# Get Tenant Detail
$tenant = Get-AzureADTenantDetail
# Now you can login to Azure PowerShell with your Service Principal and Certificate
Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId  $sp.AppId -CertificateThumbprint $thumb

如果要使用此服务主体登录Azure Rm Power Shell,还需要赋予其OwnerContributor角色。请检查此link

New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $sp.ApplicationId

然后,您可以使用以下命令登录Azure Rm powershell。

Login-AzureRmAccount -ServicePrincipal -CertificateThumbprint $Thumbprint -ApplicationId $ApplicationId -TenantId $TenantId