'MS Graph User Data Access from AAD using Java

I am trying to access MS Graph for an AAD account using Java. It is to fetch all User Data. When trying to access MS Graph I get 401 error:

            ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
                            Collections.singleton("https://graph.microsoft.com/.default"))
                    .build();

            CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);

            URL url = new URL("https://graph.microsoft.com/v1.0/users");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "Bearer " + future.get());
            conn.setRequestProperty("Accept","application/json");

            int httpResponseCode = conn.getResponseCode();
            if(httpResponseCode == HTTPResponse.SC_OK) {

                try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        responseString.append(inputLine);
                    }
                }
            }
          return responseString.toString();

Scope and other permissions are given. I am getting following result. Hope anyone can guide me to resolve the issue.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source