【Azure Developer】Azure Graph SDK獲取用戶列表的問題: SDK中GraphServiceClient如何指向中國區的Endpoint:https://microsoftgraph.chinacloudapi.cn/v1.0

問題描述

想通過Java SDK的方式來獲取Azure 門戶中所列舉的用戶。一直報錯無法正常調用介面,錯誤資訊與AAD登錄認證相關,提示tenant not found。

想要實現的目的,通過程式碼方式獲取如下User List(//portal.azure.cn/#blade/Microsoft_AAD_IAM/UsersManagementMenuBlade/MsGraphUsers

JAVA 程式碼

錯誤截圖

如何來解決獲取AAD認證的問題呢?

 

解決方法

在程式碼中,已經設置了AAD登錄Scopes 為China Azure (//microsoftgraph.chinacloudapi.cn/.default)。 但是GraphServiceClient對象依舊導向到Global的Endpoint,在查看GraphServiceClient的源碼發現它為固定值(“//graph.microsoft.com/v1.0”)。而該類沒有提供可以重寫該參數的方法,導致在最終請求時,每次生成的GraphServiceClient對象都無法請求到china的Endpoint。

 

這也就導致了即使輸入正確China AAD認證資訊但依舊無法登錄成功。最後,找到了一個Graph擴展類中的IGraphServiceClient類,它提供了setServiceRoot的方法,需要引用import com.microsoft.graph.models.extensions.IGraphServiceClient;

然後在程式碼中修改GraphServiceClient定義(程式碼中高亮部分

package GraphTest;
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; public class TestBase_Customer_Solve { private String clientId=""; private String clientSecret=""; private String grantType = "client_credentials"; private String tokenEndpoint = "//login.partner.microsoftonline.cn/{teantId}/oauth2/v2.0/token"; private String resourceId = "//microsoftgraph.chinacloudapi.cn/.default"; private String teantId = ""; public IGraphServiceClient graphClient = null; public IGraphServiceClient GetClient(boolean authenticate) { if (graphClient == null) { try { ArrayList<String> scope = new ArrayList(); scope.add( resourceId ); ClientCredentialProvider authProvider = new ClientCredentialProvider( clientId, scope, clientSecret, teantId, NationalCloud.China); graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient(); graphClient.setServiceRoot( "//microsoftgraph.chinacloudapi.cn/v1.0" ); return graphClient; } catch (Exception e) { throw new Error("Could not create a graph client: " + e.getLocalizedMessage()); } } return null; } }

在修改了Graph Client的Service Root為//microsoftgraph.chinacloudapi.cn/v1. 最終是成功拿到了Users的列表數據。

 

參考資料

msgraph-sdk-java-auth//github.com/microsoftgraph/msgraph-sdk-java-auth 

Get a GraphServiceClient object//github.com/microsoftgraph/msgraph-sdk-java#23-get-a-graphserviceclient-object