Java sharepoint via ms-graph now returning 500 error

Davesh Patel 6 Reputation points
2021-04-26T09:57:39.49+00:00

Hi,
We have some code that will do a query to find all sites using the java ms graph libraries.

    IDriveCollectionPage drives = graphClient.drives().buildRequest().get();

    ISiteCollectionPage sitesPage = graphClient.sites().buildRequest().  get();

Checked that the application registration in Azure has NOT changed.

The first line still works, however the second line has suddenly started to fail with the error :

500 : Internal Server Error
Cache-Control : no-cache
client-request-id : 6bc81403-33ca-4aae-84d3-7b711ef12b6b
Content-Type : application/json
Date : Mon, 26 Apr 2021 08:10:34 GMT
request-id : e3004346-4297-4864-9802-cc17b81e875e
Strict-Transport-Security : max-age=31536000
Transfer-Encoding : chunked
Vary : Accept-Encoding
x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"UK South","Slice":"E","Ring":"3","ScaleUnit":"000","RoleInstance":"LN2PEPF000039ED"}}
{
  "error": {
    "code": "generalException",
    "message": "An assertion failed while processing this request",
    "innerError": {
      "code": "assertionFailed",
      "date": "2021-04-26T08:10:34",
      "request-id": "e3004346-4297-4864-9802-cc17b81e875e",
      "client-request-id": "6bc81403-33ca-4aae-84d3-7b711ef12b6b"
    }
  }
}

Full Code:
************** FULL CODE *************************************************
'''
package com.example.testsharepoint;

import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.graph.models.extensions.IGraphServiceClient;
import com.microsoft.graph.requests.extensions.GraphServiceClient;
import com.microsoft.graph.requests.extensions.IDriveCollectionPage;
import com.microsoft.graph.requests.extensions.ISiteCollectionPage;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;

@Component
public class SharepointAdapter {

private static final transient Logger log = LoggerFactory.getLogger(SharepointAdapter.class);
private String accessToken = null;
private String clientId = "XXX";
private String clientSecret = "XXX";
private String tennantId = "XXX";

protected final static String authority = "https://login.microsoftonline.com/";
public static final String DefaultScope = "https://graph.microsoft.com/.default";
protected Set<String> scopeSet = new HashSet<String>();
private ConfidentialClientApplication app;
protected IAuthenticationResult result;

private IGraphServiceClient graphClient = null;
private SimpleAuthProvider authProvider = null;


public SharepointAdapter()
{

}

@PostConstruct
public  void init() throws Exception {
    getUserAccessToken();
}

public void getUserAccessToken() throws Exception {

    app = ConfidentialClientApplication.builder(
            clientId,
            ClientCredentialFactory.createFromSecret(clientSecret))
            .authority(authority + tennantId + "/")
            .build();

    String[] appScopes = DefaultScope.split(",");
    CollectionUtils.addAll(scopeSet, appScopes);

   ClientCredentialParameters.ClientCredentialParametersBuilder builder = ClientCredentialParameters.builder(scopeSet);
    ClientCredentialParameters clientCredentialParam = builder.build();

    if ( log.isDebugEnabled())
    {
        log.debug("{} Getting token...", getLogPrefix());
    }

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

    BiConsumer<IAuthenticationResult, Throwable> processAuthResult = (res, ex) -> {
        if (ex != null) {
            Throwable error = ex.getCause();
            if (error != null) {
                log.error("{}Error connecting to Microsoft - {}", getLogPrefix(), error.getMessage());
            } else {
                log.error("{}Error connecting to Microsoft - {}", getLogPrefix(), ex.getMessage());
            }
        }
    };

    future.whenCompleteAsync(processAuthResult);
    future.join();

    result = future.get();
    if (result == null) {
        throw new Exception("Unable to connect to Microsoft, did not get an authentication token.");
    }

    if ( log.isTraceEnabled())
    {
        log.trace("{}: TOKEN: {}", getLogPrefix(), result.accessToken() );
    }

    String token = result.accessToken();
    authProvider = new SimpleAuthProvider(token);
    // Build a Graph client
    graphClient = GraphServiceClient.builder()
            .authenticationProvider(authProvider)
            .logger(MSLogger.getLogger())
            .buildClient();

    IDriveCollectionPage drives = graphClient.drives().buildRequest().get();

    ISiteCollectionPage sitesPage = graphClient.sites().buildRequest().  get();
}

protected String getLogPrefix()
{
    return "[ Client ID: "+ clientId + "] ";
}

}

Relevant Maven Versions:

    <java.version>14</java.version>
    <spring-cloud.version>Hoxton.SR10</spring-cloud.version>
    <springframework.boot.version>2.3.9.RELEASE</springframework.boot.version>
    <microsoft-msal4j-version>1.9.1</microsoft-msal4j-version>
    <microsoft-graph-version>2.10.0</microsoft-graph-version>
    <azure.version>3.2.0</azure.version>

Thanks in advance,

Microsoft 365 and Office | SharePoint | For business | Windows
Microsoft Security | Microsoft Graph
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Davesh Patel 6 Reputation points
    2021-04-26T14:09:43.273+00:00

    For anyone else who has this issue, found the following change made the call successful:

    LinkedList<Option> requestOptions = new LinkedList<Option>();
    requestOptions.add(new QueryOption("search", "*"));
    ISiteCollectionPage sitesPage = graphClient.sites().buildRequest(requestOptions).get();
    

    Not sure why the old code suddenly stopped working, but this has fixed it.


  2. Anonymous
    2021-04-26T15:33:00.513+00:00

    Thanks for sharing this solution.
    But did you notice a change in the response now. I found some of the sites missing. @Davesh Patel


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.