【Azure 环境】使用Microsoft Graph PS SDK 登录到中国区Azure, 命令Connect-MgGraph -Environment China xxxxxxxxx 遇见登录错误

问题描述

通过PowerShell 连接到Microsoft Graph 中国区Azure,一直出现AADSTS700016错误, 消息显示 the specific application was not installed in your tenant.

 

解决办法

根据弹出框中的错误提示, 这是因为MS Graph PowerShell并没有注册到中国区Azure环境中,所以它无法找到Applicaiton ID: '14d82eec-204b-4c2f-b7e8-296a70dab67e'。

可以使用以下脚本进行验证:

Get-AzureADApplication -Filter "AppId eq '14d82eec-204b-4c2f-b7e8-296a70dab67e'" 

为了解决这个问题,需要自己在Azure AD中主动注册一个Application,然后使用这个Application Id进行相应操作。需要执行的操作有:

1)登录到Azure AD 页面,注册一个App (Registered App: https://portal.azure.cn/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps

2)赋予这个App相应的操作权限,如 User.Read.All, Group.ReadWrite.All 等

3)生成一个证书,并上传到App中

#  生成自签名证书
$Cert = New-SelfSignedCertificate -DnsName icy-ps-sdk-aad -CertStoreLocation "Cert:\CurrentUser\My" -FriendlyName "MicrosoftGraphSDK" -Subject "Test Cert for Microsoft Graph SDK"

 

 4)在本地也安装同样的证书。

 

完成以上四步后,就可以使用以下的代码登录中国区Graph了。

#需要选择从本地选择证书,完成登录
Connect-MgGraph -Scopes "User.Read.All" -ClientId "你的appid=clientid" -Environment China -UseDeviceAuthentication 


# 直接登录方式
Connect-MgGraph -Environment China -AppId "你的App ID" -TenantId "你的Tenant ID" -CertificateThumbprint "证书指纹 Thumbprint" -Debug

 

 

附录: 完整的脚本

# 生成证书文件
$Cert = New-SelfSignedCertificate -DnsName icy-ps-sdk-aad -CertStoreLocation "Cert:\CurrentUser\My" -FriendlyName "MicrosoftGraphSDK" -Subject "Test Cert for Microsoft Graph SDK"
Get-ChildItem "Cert:\CurrentUser\My\$($Cert.thumbprint)"
Get-ChildItem "Cert:\CurrentUser\My\$($Cert.thumbprint)" | Export-Certificate -FilePath C:\temp\MicrosoftGraphSDK.cer 

#登录
Connect-MgGraph -Scopes "User.Read.All" -ClientId "your clientid" -Environment China -TenantId “your tenant id” -UseDeviceAuthentication

Connect-MgGraph -Scopes "User.Read.All" -ClientId "your clientid" -Environment China -TenantId “your tenant id” -CertificateThumbprint "certificate thumbprint"

#获取User 
Get-MgUser

get-mgcontext 

#退出登录
Disconnect-MgGraph

 

参考资料

Get started with the Microsoft Graph PowerShell SDK:https://docs.microsoft.com/en-us/powershell/microsoftgraph/get-started?view=graph-powershell-beta

posted @ 2022-04-23 14:23  路边两盏灯  阅读(653)  评论(0编辑  收藏  举报