問題描述
想通過Java SDK的方式來獲取Azure 門戶中所列舉的用戶。一直報錯無法正常調用接口艺晴,錯誤信息與AAD登錄認證相關弃理,提示tenant not found。
想要實現的目的悠栓,通過代碼方式獲取如下User List(https://portal.azure.cn/#blade/Microsoft_AAD_IAM/UsersManagementMenuBlade/MsGraphUsers)
JAVA 代碼
錯誤截圖
如何來解決獲取AAD認證的問題呢?
解決方法
在代碼中,已經設置了AAD登錄Scopes 為China Azure (https://microsoftgraph.chinacloudapi.cn/.default)按价。 但是GraphServiceClient對象依舊導向到Global的Endpoint惭适,在查看GraphServiceClient的源碼發(fā)現它為固定值("https://graph.microsoft.com/v1.0")。而該類沒有提供可以重寫該參數的方法,導致在最終請求時,每次生成的GraphServiceClient對象都無法請求到china的Endpoint驻啤。
這也就導致了即使輸入正確China AAD認證信息但依舊無法登錄成功。最后凄杯,找到了一個Graph擴展類中的IGraphServiceClient類错洁,它提供了setServiceRoot的方法,需要引用import com.microsoft.graph.models.extensions.IGraphServiceClient;
然后在代碼中修改GraphServiceClient定義(代碼中高亮部分)
packageGraphTest;
import com.microsoft.graph.auth.confidentialClient.ClientCredentialProvider;import com.microsoft.graph.auth.enums.NationalCloud;import com.microsoft.graph.models.extensions.IGraphServiceClient;import com.microsoft.graph.requests.extensions.GraphServiceClient;import java.util.ArrayList;publicclass TestBase_Customer_Solve {
? ? privateString clientId="";
? ? privateString clientSecret="";
? ? privateString grantType = "client_credentials";
? ? privateString tokenEndpoint = "https://login.partner.microsoftonline.cn/{teantId}/oauth2/v2.0/token";
? ? privateString resourceId = "https://microsoftgraph.chinacloudapi.cn/.default";
? ? privateString teantId = "";
? ? publicIGraphServiceClient graphClient =null;
? ? publicIGraphServiceClient GetClient(boolean authenticate)
? ? {
? ? ? ? if(graphClient ==null) {
? ? ? ? ? ? try {
ArrayList?scope =new ArrayList();
? ? ? ? ? ? ? ? scope.add( resourceId );
? ? ? ? ? ? ? ? ClientCredentialProvider authProvider =new ClientCredentialProvider(
? ? ? ? ? ? ? ? ? ? ? ? clientId,
? ? ? ? ? ? ? ? ? ? ? ? scope,
? ? ? ? ? ? ? ? ? ? ? ? clientSecret,
? ? ? ? ? ? ? ? ? ? ? ? teantId,
? ? ? ? ? ? ? ? ? ? ? ? NationalCloud.China);
? ? ? ? ? ? ? ? graphClient =GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();graphClient.setServiceRoot( "https://microsoftgraph.chinacloudapi.cn/v1.0" );return graphClient;
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception e)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? thrownewError("Could not create a graph client: " + e.getLocalizedMessage());
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? returnnull;
? ? }
}
在修改了Graph Client的Service Root為https://microsoftgraph.chinacloudapi.cn/v1. 最終是成功拿到了Users的列表數據戒突。
參考資料
msgraph-sdk-java-auth:https://github.com/microsoftgraph/msgraph-sdk-java-auth
GraphServiceClient.java:https://github.com/microsoftgraph/msgraph-sdk-java/blob/4638206053a5545a6d6ba73168337939cde34fed/src/main/java/com/microsoft/graph/requests/GraphServiceClient.java
Get a GraphServiceClient object:https://github.com/microsoftgraph/msgraph-sdk-java#23-get-a-graphserviceclient-object