How to fetch onPermisesSamAccountName along with default attributes of an user in azure ad sdk java

64 Views Asked by At

My azure ad sdk code to fetch all the users from a tenant is as follows

List<User> users = new ArrayList<>();
    try {
            
                UserCollectionRequestBuilder usersClientBuilder = graphClient.users();
                UserCollectionRequest usersRequest = usersClientBuilder.buildRequest();
                do {
                    UserCollectionPage userCollectionPage = usersRequest.get();
                    users.addAll(userCollectionPage.getCurrentPage());
                    usersClientBuilder = userCollectionPage.getNextPage();
                    if (usersClientBuilder == null) {
                        usersRequest = null;
                    } else {
                        usersRequest = usersClientBuilder.buildRequest();
                    }
                } while (usersRequest != null);
                
            } catch (GraphServiceException e) {
                log.error("GraphServiceException occurred in getAllUsers() : ", e);
}

This code returns the following attributes

{
        "businessPhones": [],
        "displayName": "avinash#kumar2",
        "givenName": "Avinash",
        "jobTitle": null,
        "mail": "[email protected]",
        "mobilePhone": null,
        "officeLocation": null,
        "preferredLanguage": null,
        "surname": "Kumar2",
        "userPrincipalName": "avinash#[email protected]",
        "id": "217ae76c-585b-44be-864a-e33a764ff199"
    },

Along with the above data, we also need to fetch onPremsisesSamAccountName. I was going through the documents of azure ad sdk and figured out that we need Optional query parameters such as $select to fetch the onPremisesSamAccountName.

When i tried this in postman it returns only the attribute we specify in select

For ex :

enter image description here

But the requirement is we need to get the default attributes along with onPremsisesSamAccountName.

Since i am using azure ad sdk in java i have tried this code, but it does not work and gives me an error

List<User> users = new ArrayList<>();
        
            try {
                List<Option> requestOptions = new ArrayList<Option>();
                requestOptions.add(new QueryOption("$select", "'=onPremisesSamAccountName'"));
                requestOptions.add(new QueryOption("$count", "true"));
                requestOptions.add(new HeaderOption("ConsistencyLevel", "eventual"));
                Instant start = Instant.now();
                UserCollectionRequestBuilder usersClientBuilder = graphClient.users();
                UserCollectionRequest usersRequest = usersClientBuilder.buildRequest(requestOptions);
                do {
                    UserCollectionPage userCollectionPage = usersRequest.get();
                    users.addAll(userCollectionPage.getCurrentPage());
                    usersClientBuilder = userCollectionPage.getNextPage();
                    if (usersClientBuilder == null) {
                        usersRequest = null;
                    } else {
                        usersRequest = usersClientBuilder.buildRequest();
                    }
                } while (usersRequest != null);
            } catch (GraphServiceException e) {
                log.error("GraphServiceException occurred in getAllUsers() : ", e);
                
            }

The error is as below

EVERE: CoreHttpProvider[sendRequestInternal] - 408Graph service exception
Mar 19, 2024 6:57:51 PM com.microsoft.graph.logger.DefaultLogger logError
SEVERE: Throwable detail: com.microsoft.graph.http.GraphServiceException: Error code: BadRequest
Error message: Parsing OData Select and Expand failed: An identifier was expected at position 0.

GET https://graph.microsoft.com/v1.0/users?%24select=%3DonPremisesSamAccountName
SdkVersion : graph-java/v5.53.0


400 : 
[...]

[Some information was truncated for brevity, enable debug logging for more details]

Any help/suggestions please.

1

There are 1 best solutions below

0
Sridevi On

When you use $select in your Microsoft Graph query, it will limit the query response by displaying only specified properties like this:

GET https://graph.microsoft.com/v1.0/users?$select=onPremisesSamAccountName

Response:

enter image description here

To fetch onPermisesSamAccountName along with default attributes of users, you need to include those attributes too with $select parameter like this:

GET https://graph.microsoft.com/v1.0/users?$select=businessPhones,displayName,givenName,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,id,onPremisesSamAccountName

Response:

enter image description here

To get the same response having onPermisesSamAccountName with default attributes of users in Java SDK, you can refer this sample code:

import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import com.microsoft.graph.models.User;
import com.microsoft.graph.requests.GraphServiceClient;
import com.microsoft.graph.requests.UserCollectionPage;

import java.util.Arrays;
import java.util.List;

public class AzureADUserAuth {
    final String clientId = "appId";
    final String tenantId = "tenantId";
    final String clientSecret = "secret";
    final List<String> scopes = Arrays.asList("https://graph.microsoft.com/.default");

    public static void main(String[] args) {
        try {
            AzureADUserAuth azureADUserAuth = new AzureADUserAuth();
            azureADUserAuth.authenticateAndFetchUsers();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void authenticateAndFetchUsers() throws Exception {
        ClientSecretCredential credential = new ClientSecretCredentialBuilder()
                .clientId(clientId).tenantId(tenantId).clientSecret(clientSecret)
                .build();

        if (null == scopes || null == credential) {
            throw new Exception("Unexpected error");
        }

        TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(scopes, credential);
        GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();

        // Specify the properties to retrieve using $select
        UserCollectionPage users = graphClient.users().buildRequest().select("businessPhones,displayName,givenName,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,id,onPremisesSamAccountName").get();
        for (User user : users.getCurrentPage()) {
            // Print all user properties
            System.out.println("Display Name: " + user.displayName);
            System.out.println("Given Name: " + user.givenName);
            System.out.println("Surname: " + user.surname);
            System.out.println("User Principal Name: " + user.userPrincipalName);
            System.out.println("Mail: " + user.mail);
            System.out.println("Job Title: " + user.jobTitle);
            System.out.println("Mobile Phone: " + user.mobilePhone);
            System.out.println("Office Location: " + user.officeLocation);
            System.out.println("Preferred Language: " + user.preferredLanguage);
            System.out.println("Business Phones: " + user.businessPhones);
            System.out.println("ID: " + user.id);
            System.out.println("onPremisesSamAccountName: " + user.onPremisesSamAccountName);
            System.out.println("----------------------------------------");
        }
    }
}

Response:

enter image description here

Reference: Use query parameters to customize responses - Microsoft Graph