Search code examples
javamicrosoft-graph-apiazure-java-sdkazure-identity

Having trouble implementing Microsoft Graph Java SDK to list licenses assigned to user


I'm currently working on integrating Microsoft Graph APIs into my Java application to retrieve license details for users in my Microsoft 365 tenant. I referred to the official Microsoft documentation here to understand the usage of the Microsoft Graph Java SDK for this purpose. However, despite following the provided guidance, I'm encountering difficulties in implementing the solution within my Java codebase.

Context:

  • I'm utilizing the Microsoft Graph Java SDK to interact with Microsoft 365 APIs.
  • Specifically, I'm referring to the documentation for listing license details for a user here.
  • My authentication setup and GraphServiceClient instantiation are already in place, following the documentation.

Issue: The code snippet provided in the documentation is as follows:


// Code snippets are only available for the latest version. Current version is 6.x

GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);

LicenseDetailsCollectionResponse result = graphClient.users().byUserId("{user-id}").licenseDetails().get();

I've attempted to integrate this code into my Java application. While I can successfully query the Microsoft Graph API using tools like Postman, I'm unable to replicate the functionality within my Java codebase.

Expectation: I'm seeking assistance in understanding and resolving the following:

  1. How can I properly configure the requestAdapter required for initializing the GraphServiceClient instance in Java?

  2. Are there any additional configurations or dependencies required to make the Microsoft Graph Java SDK work seamlessly within a Java application?

I appreciate any insights or guidance on how to resolve this issue and successfully retrieve license details for users using the Microsoft Graph Java SDK within my Java application.


Solution

  • When I ran below HTTP call in Graph Explorer, I got the response with list of license details successfully like this:

    GET https://graph.microsoft.com/v1.0/users/userId/licenseDetails
    

    Response:

    enter image description here

    To get the same response using Microsoft Graph Java SDK, you can make use of below sample code:

    GraphAPIClient.java:

    import com.azure.identity.ClientSecretCredential;
    import com.azure.identity.ClientSecretCredentialBuilder;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
    import com.microsoft.graph.models.LicenseDetails;
    import com.microsoft.graph.models.ServicePlanInfo;
    import com.microsoft.graph.requests.GraphServiceClient;
    import com.microsoft.graph.requests.LicenseDetailsCollectionPage;
    
    import java.util.Arrays;
    import java.util.List;
    
    public class GraphAPIClient {
        // Azure AD authentication credentials
        final String clientId = "appId";
        final String tenantId = "tenantId";
        final String clientSecret = "secret";
        final List<String> scopes = Arrays.asList("https://graph.microsoft.com/.default");
    
        final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    
        public static void main(String[] args) {
            GraphAPIClient graphAPIClient = new GraphAPIClient();
            graphAPIClient.fetchAndListLicenseDetails();
        }
    
        public void fetchAndListLicenseDetails() {
            // Authenticate with Azure AD
            ClientSecretCredential credential = new ClientSecretCredentialBuilder()
                    .clientId(clientId).tenantId(tenantId).clientSecret(clientSecret)
                    .build();
    
            TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(scopes, credential);
            GraphServiceClient<GraphServiceClient> graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
    
            // Fetch and list license details of the user
            try {
                LicenseDetailsCollectionPage licenseDetailsCollection = graphClient.users("userId").licenseDetails().buildRequest().get();
    
                while (licenseDetailsCollection != null) {
                    for (LicenseDetails licenseDetail : licenseDetailsCollection.getCurrentPage()) {
                        System.out.println("\nLicense ID: " + licenseDetail.id);
                        System.out.println("Service Plans:");
                        for (ServicePlanInfo servicePlanInfo : licenseDetail.servicePlans) {
                            System.out.println("\tService Plan ID: " + servicePlanInfo.servicePlanId);
                            System.out.println("\tService Plan Name: " + servicePlanInfo.servicePlanName);
                        }
                        System.out.println("----------------------------------");
    
                        // Convert object to JSON string with pretty printing
                        String json = gson.toJson(licenseDetail);
                        System.out.println("Complete JSON response:");
                        System.out.println(json);
                    }
    
                    if (licenseDetailsCollection.getNextPage() == null) {
                        break;
                    }
    
                    licenseDetailsCollection = licenseDetailsCollection.getNextPage().buildRequest().get();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    pom.xml

        <dependencies>
            <dependency>
                <groupId>com.microsoft.graph</groupId>
                <artifactId>microsoft-graph</artifactId>
                <version>3.0.0</version>
            </dependency>
            <dependency>
                <groupId>com.azure</groupId>
                <artifactId>azure-identity</artifactId>
                <version>1.3.0</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>1.2.6</version>
            </dependency>
        </dependencies>
    

    Response:

    enter image description here