你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

在 PowerShell 中使用服务主体连接到目录

本示例介绍如何在 PowerShell 中使用服务主体连接到目录。 如果想要像运行 Windows 计划任务一样运行无人参与的脚本,可以使用此方法。

若要启用此功能,需要执行几个步骤。

使用管理员帐户登录到 Azure AD PowerShell

首先,需要使用管理员帐户登录到 PowerShell 会话:

Connect-AzureAD

创建自签名证书

本示例将使用自签名证书,因此,让我们创建一个。 你需要将以下示例中的密码字符串替换为 <所选的密码> ,这是用于创建证书文件的密码。

$pwd = "<password>"
$notAfter = (Get-Date).AddMonths(6) # Valid for 6 months
$thumb = (New-SelfSignedCertificate -DnsName "drumkit.onmicrosoft.com" -CertStoreLocation "cert:\LocalMachine\My"  -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

加载证书

创建证书文件后,需要加载该文件,以便可以将其分配到要创建的新应用程序:

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

创建 Azure Active Directory 应用程序

下一步是创建新应用程序,并将创建的证书分配为密钥凭据:

$application = New-AzureADApplication -DisplayName "test123" -IdentifierUris "https://rodejo2177668"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "Test123" -Type AsymmetricX509Cert -Usage Verify -Value $keyValue -EndDate $notAfter

创建服务主体并将其连接到应用程序

若要在 PowerShell 中使用应用程序登录到目录,需要为此应用程序创建新的服务主体:

$sp=New-AzureADServicePrincipal -AppId $application.AppId 

授予对当前租户的“服务主体读取者”访问权限 (Get-AzureADDirectoryRole)

现在,我们可以在目录中设置此服务主体的确切访问权限。 在此示例中,我们会在 Azure AD 中分配“目录读取者”角色的访问权限:

Add-AzureADDirectoryRoleMember -ObjectId (Get-AzureADDirectoryRole | where-object {$_.DisplayName -eq "Directory Readers"}).Objectid -RefObjectId $sp.ObjectId 

本示例的设置部分到此结束。

登录到租户

现在,我们可以使用新服务主体立即登录到目录。

注意:如果在一个脚本中运行所有这些命令,正如尝试此操作时可能所做的那样,请记住,Azure AD 需要一段时间才能同步刚通过其所有组件输入的所有信息。 在这种情况下,可在此处添加一个 Sleep cmdlet 调用,使脚本处理暂停 5 秒:

Sleep -s 5 

若要登录,需要找到所要登录到的租户的 ObjectID:

$tenant=Get-AzureADTenantDetail

现在,可以使用服务主体和证书登录到 Azure AD PowerShell 目录

Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId  $Application.AppId -CertificateThumbprint $thumb