You can add a user to an Azure Active Directory (Azure AD) group using C# code by leveraging the Microsoft Graph API, which allows you to interact with Azure AD resources programmatically. Here's a step-by-step guide on how to achieve this:

Prerequisites:

  1. You need an Azure AD tenant with appropriate permissions to manage groups and users.
  2. Register your application in Azure AD and grant it the necessary permissions to manage groups and users. You can do this through the Azure portal.

Code to Add a User to an Azure AD Group:
Make sure you have the Microsoft Graph SDK installed in your C# project. You can install it via NuGet using the following command:

Install-Package Microsoft.Graph

Now, you can use the following C# code to add a user to an Azure AD group:

using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Define your Azure AD application settings
        string clientId = "YourClientId";
        string clientSecret = "YourClientSecret";
        string tenantId = "YourTenantId";

        // Initialize the MSAL and client credentials
        IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
            .Build();

        ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

        // Create a GraphServiceClient
        GraphServiceClient graphClient = new GraphServiceClient(authProvider);

        // Define the user's and group's IDs
        string userId = "UserIdToAdd"; // Replace with the actual user's ID
        string groupId = "GroupIdToAddTo"; // Replace with the actual group's ID

        try
        {
            // Add the user to the group
            await graphClient.Groups[groupId].Members.References.Request().AddAsync(new DirectoryObject { Id = userId });
            Console.WriteLine("User added to the group successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error adding user to the group: {ex.Message}");
        }
    }
}

Replace the placeholders (YourClientId, YourClientSecret, YourTenantId, UserIdToAdd, and GroupIdToAddTo) with your Azure AD application's information and the actual user and group IDs you want to use.
This code initializes an application with the necessary permissions, creates a GraphServiceClient, and uses it to add a user to a group in Azure AD. Make sure that your application has the required permissions to modify groups and users in Azure AD.

References: