使用 UsernamePasswordCredential 提供程序列出 Azure AD

List Azure AD using UsernamePasswordCredential provider

我正在使用 UsernamePasswordCredential 提供程序连接到 AAD 并使用 msgraph-sdk-java (https://github.com/microsoftgraph/msgraph-sdk-java) 获取用户,代码如下:

            final UsernamePasswordCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder()
                .clientId("client_id")
                .username("user_name")                             
                .password("password")
                .build();

        final TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(Arrays.asList("https://graph.microsoft.com/.default"), usernamePasswordCredential);

        final GraphServiceClient graphClient =
          GraphServiceClient
            .builder()
            .authenticationProvider(tokenCredentialAuthProvider)
            .buildClient();

        UserCollectionPage userCollectionpage = graphClient.users().buildRequest().get();

我收到以下错误:

java.io.IOException: java.util.concurrent.ExecutionException: com.azure.core.exception.ClientAuthenticationException: Failed to acquire token with username and password

知道我是否需要在 Azure 活动目录中配置一些东西吗?

您的问题已通过评论解决。 Post 它作为结束线程的答案:

  1. 确保您的帐户不是个人帐户。

  2. 确保启用 Allow public client flows

  1. 使用 msal4j 库和 PublicClientApplication class 获取带有用户名、密码和范围的令牌。