Deleting USERS from Azure B2C Active in Java [graphClient.users(user-id).buildRequest().delete()]

Viewed 139

I am trying to migrate users to Azure B2C Active Directory.

Earlier I was creating "users" that I was reading from a JSON file and creating them, however if any "user" in the JSON was already present in Azure B2C AD, I was getting an exception...

SEVERE: Throwable detail: com.microsoft.graph.http.GraphServiceException: Error code: Request_BadRequest
Error message: Another object with the same value for property userPrincipalName already exists.

I was handling all those "users" with a simple try/catch and skipping them and moving them to next user in the JSON.

Now I need to delete the existing user in the process (Once I get above exception, I will delete the user)

I tried this...

private void deleteExistingUser(String issuerAssignedId, IGraphServiceClient graphClient) {
    graphClient.users(issuerAssignedId).buildRequest().delete();
    LOG.info("User deleted.");
}

But when above code is hit I am getting below exception...

Error message: Resource 'shumi' does not exist or one of its queried reference-property objects are not present.

Can you tell me how can I get in here graphClient.users(what_value_will_go_here).buildRequest().delete();

I believe this is happening because I am using userPrincipalName (issuerAssignedId) to delete the user, Instead I should be using "azure retured user id" (it is called Object-id OR user-id I think) to delete the user.

Is there a way I can get azure returned user id or some other way to delete the user?

2 Answers

Use IUserCollectionPage and QueryOption to get a List.

        LinkedList<QueryOption> requestOptions = new LinkedList<>();
        
        String query = "identities/any(c:c/issuerAssignedId eq ' issuerAssignedId ' 
        and c/issuer eq ' b2cTenant ')";
        
        requestOptions.add(new QueryOption("$filter", query));
        
        IUserCollectionPage userColl = graphClient.users()
                .buildRequest(requestOptions)
                .get();
        
        List<User> userInfo = userColl.getCurrentPage();
        
        String uId = null;
        
        for (User user : userInfo) {
            userId = user.id;
        }
        
        graphClient.users(uId).buildRequest().delete();

This is how you can delete a User from Azure b2c AD

Note : b2Tenant is "demo.micorsoft.com" (use yours)

You should put User object id or userPrincipalName here.

You use "shumi" here because its signInType is userName.

Since you get the error Error message: Another object with the same value for property userPrincipalName already exists., I think you already have the userPrincipalName.

You don't need to get the user id. Just delete the user like this:

await graphClient.Users["{userPrincipalName}"]
    .Request()
    .DeleteAsync();
Related