azureazure-active-directoryazure-java-sdk

How to authenticate to Azure AD using java SDK


I am trying to create an authentication method to autheticate to azure ad for adding an removal of users via my java code. I have a free tier account setup for the same. below is the method I used for authentication:

   try {
            final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
            final TokenCredential credential = new DefaultAzureCredentialBuilder()
                .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
                .build();

            AzureResourceManager azureResourceManager = AzureResourceManager
                .configure()
                .withLogLevel(HttpLogDetailLevel.BASIC)
                .authenticate(credential, profile)
                .withDefaultSubscription();

            runSample(azureResourceManager, profile);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

public static boolean runSample(AzureResourceManager azureResourceManager, AzureProfile profile) {
        final String userEmail = Utils.randomResourceName(azureResourceManager, "test", 15);
        final String userName = userEmail.replace("test", "Test ");
        final String spName = Utils.randomResourceName(azureResourceManager, "sp", 15);
        final String raName1 = Utils.randomUuid(azureResourceManager);
        final String raName2 = Utils.randomUuid(azureResourceManager);
        final String groupEmail1 = Utils.randomResourceName(azureResourceManager, "group1", 15);
        final String groupEmail2 = Utils.randomResourceName(azureResourceManager, "group2", 15);
        final String groupName1 = groupEmail1.replace("group1", "Group ");
        final String groupName2 = groupEmail2.replace("group2", "Group ");
        String spId = "";
        try {
            // ============================================================
            // Create a user

            System.out.println("Creating an AD user " + userName + "...");
//
            ActiveDirectoryUser user = azureResourceManager.accessManagement().activeDirectoryUsers()
                    .define(userName)
                    .withEmailAlias(userEmail)
                    .withPassword(Utils.password())
                    .create();
//
            System.out.println("Created AD user " + userName);
            Utils.print(user);

            } catch (Exception e) {
                System.out.println("Did not create Service Principal in Azure. No clean up is necessary");
            }
}

I passed enter image description here

these details in the environment. Where client secret I extracted after registering an application in the portal. I am not able to complete the authentication by the above logic. Can anyone please help me here ?


Solution

  • You can make use of Microsoft Graph Java SDK to authenticate Azure AD for user's addition and removal.

    Initially, I registered one application and granted User.ReadWrite.All permission of Application type with consent as below:

    enter image description here

    Now, I created one client secret in above app registration and noted it's value like this:

    enter image description here

    In my case, I ran below sample code to create user in Azure AD and got response like this:

    Main.java:

    package org.example;
    
    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.models.PasswordProfile;
    import com.microsoft.graph.requests.GraphServiceClient;
    import okhttp3.Request;
    import java.util.Arrays;
    import java.util.List;
    
    public class Main {
        private static final String CLIENT_ID = "appId";
        private static final String CLIENT_SECRET = "secretValue";
        private static final String TENANT_ID = "tenantId";
    
        public static void main(String[] args) {
            try {
                ClientSecretCredential credential = new ClientSecretCredentialBuilder()
                        .clientId(CLIENT_ID)
                        .clientSecret(CLIENT_SECRET)
                        .tenantId(TENANT_ID)
                        .build();
    
                List<String> scopes = Arrays.asList("https://graph.microsoft.com/.default");
                TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(
                        scopes,
                        credential
                );
    
                GraphServiceClient<Request> graphClient = GraphServiceClient
                        .builder()
                        .authenticationProvider(authProvider)
                        .buildClient();
    
                createUser(graphClient);
    
                // delete a user
                // deleteUser(graphClient, "<USER_ID>");
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static void createUser(GraphServiceClient<Request> graphClient) {
            User user = new User();
            user.displayName = "User Name";
            user.mailNickname = "username";
            user.userPrincipalName = "username@yourdomain.onmicrosoft.com";
            user.accountEnabled = true;
            user.passwordProfile = new PasswordProfile();
            user.passwordProfile.password = "P@ssw0rd!";
            user.passwordProfile.forceChangePasswordNextSignIn = false;
    
            User createdUser = graphClient.users()
                    .buildRequest()
                    .post(user);
    
            System.out.println("Created User with ID: " + createdUser.id);
            System.out.println("Created User with Name: " + createdUser.displayName);
        }
    
        private static void deleteUser(GraphServiceClient<Request> graphClient, String userId) {
            graphClient.users(userId)
                    .buildRequest()
                    .delete();
            System.out.println("Deleted User with ID: " + userId);
        }
    }
    

    Response:

    enter image description here

    To confirm that, I checked the same in Portal where new user created successfully as below:

    enter image description here

    Before executing the code above, ensure that the necessary dependencies are installed in your Java project:

    pom.xml:

    <dependencies>
            <!-- Azure Identity library for authentication -->
            <dependency>
                <groupId>com.azure</groupId>
                <artifactId>azure-identity</artifactId>
                <version>1.6.0</version>
            </dependency>
            <!-- Microsoft Graph SDK for Java -->
            <dependency>
                <groupId>com.microsoft.graph</groupId>
                <artifactId>microsoft-graph</artifactId>
                <version>5.0.0</version>
            </dependency>
            <!-- Logging -->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>1.2.6</version>
            </dependency>
    </dependencies>
    

    Reference:

    Create User - Microsoft Graph v1.0