問題描述
示例調(diào)用MSGraph SDK通過User principal name獲取到User信息乳怎,如Object ID祟偷。
參考資料
選擇 Microsoft Graph 身份驗證提供程序 : https://learn.microsoft.com/zh-cn/graph/sdks/choose-authentication-providers?tabs=java#using-a-client-secret-2
Microsoft Graph SDK for Java : https://github.com/microsoftgraph/msgraph-sdk-java
Azure China developer guide : https://learn.microsoft.com/en-us/azure/china/resources-developer-guide#check-endpoints-in-azure
| Microsoft Graph | https://graph.microsoft.com | https://microsoftgraph.chinacloudapi.cn |
示例代碼
第一步:在POM.XML中添加對 com.microsoft.graph 的依賴
<dependency>
<!-- Include the sdk as a dependency -->
<groupId>com.microsoft.graph</groupId>
<artifactId>microsoft-graph</artifactId>
<version>5.73.0</version>
</dependency>
第二步:引用代碼
String clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
String clientSecret = "application secret";
String tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
// The client credentials flow requires that you request the
// /.default scope, and pre-configure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
java.util.List<String> scopes = Arrays.asList("https://microsoftgraph.chinacloudapi.cn/.default");
ClientSecretCredential credential = new ClientSecretCredentialBuilder()
.authorityHost("https://login.partner.microsoftonline.cn")
.clientId(clientId).tenantId(tenantId).clientSecret(clientSecret).build();
if (null == scopes || null == credential) {
throw new Exception("Unexpected error");
}
TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(
scopes, credential);
GraphServiceClient<okhttp3.Request> graphClient = GraphServiceClient.builder()
.authenticationProvider(authProvider).buildClient();
// Specify the user principal name
String userPrincipalName = "user principal name";
graphClient.setServiceRoot("https://microsoftgraph.chinacloudapi.cn/v1.0");
// Use the GraphServiceClient to get the user by user principal name
User user = graphClient.users(userPrincipalName)
.buildRequest()
.get();
// Get the user object ID
String objectId = user.id;
注意事項
1)因為這是在中國區(qū)Azure察滑,所以AAD認證,Graph Endpoint都想要切換到中國Azure環(huán)境
- AAD Login Endpoint: https://login.partner.microsoftonline.cn
- Ms Graph: https://microsoftgraph.chinacloudapi.cn/v1.0
2) 如果遇見403 FORBIDDEN的情況修肠,則想要為代碼中所使用的AAD注冊應用添加Microsoft.Graph的User.read.all權(quán)限
結(jié)果展示
[END]
當在復雜的環(huán)境中面臨問題贺辰,格物之道需:濁而靜之徐清,安以動之徐生嵌施。 云中饲化,恰是如此!