【Azure Developer】示例: 在中国区调用MSGraph SDK通过User principal name获取到User信息,如Object ID

问题描述

示例调用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)因为这是在中国区Azure,所以AAD认证,Graph Endpoint都想要切换到中国Azure环境

  • 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权限

结果展示

 

 

[END]

posted @ 2023-10-10 20:11  路边两盏灯  阅读(85)  评论(0编辑  收藏  举报