Search code examples
azuremicrosoft-graph-api

Identifier Expected Error - While adding members to AAD using Graph API


I am using Graph client to get details and here is the code

public static class AddUserToGroup
  {
   [FunctionName("AddUserToGroup")]
    public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
   {
    log.LogInformation("AddUserToGroup function triggered with HTTP trigger.");

    string UserPrincipalName = req.Query["UserPrincipalName"];
    string GroupId = req.Query["GroupId"];


    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    UserPrincipalName = UserPrincipalName ?? data?.UserPrincipalName;
    GroupId = GroupId ?? data?.GroupId;

    string responseMessage;
    if (UserPrincipalName.IsNullOrEmpty() || GroupId.IsNullOrEmpty())
    {
        responseMessage = "Missing Parameter.";
        return new BadRequestObjectResult(responseMessage);
    }

    var scopes = new[] { "https://graph.microsoft.com/.default" };

    var builder = new ConfigurationBuilder()
            .SetBasePath(Environment.CurrentDirectory)
            .AddJsonFile("local.settings.json", true)
            .AddUserSecrets(Assembly.GetExecutingAssembly(), true)
            .AddEnvironmentVariables()
            .Build();


    var tenantId = builder.GetValue<string>("_secret:tenantId");
    var clientId = builder.GetValue<string>("_secret:clientId");
    var clientSecret = builder.GetValue<string>("_secret:clientSecret");

    // using Azure.Identity;
    var options = new TokenCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    };

    var clientSecretCredential = new ClientSecretCredential(
        tenantId, clientId, clientSecret, options);

    var graphClient = new GraphServiceClient(clientSecretCredential, scopes);


    User userToAdd = await graphClient.Users[UserPrincipalName].GetAsync();
    await graphClient.Groups[GroupId].Members.(userToAdd);

    responseMessage = "User added to the group successfully.";

    log.LogInformation("AddUserToGroup function processing finished.");
    return new OkObjectResult(responseMessage);
}

}

Packages Used:

Microsoft.Graph 5.56 version

Here is the error screenshot which shows the error.

I am following the code from https://github.com/microsoft/AzureProvisioningUsingFunctions/tree/main

enter image description here


Solution

  • To get the users using 'UserPrincipalName' and add it to AAD group, modify the code like below:

    using Microsoft.Graph;
    using Azure.Identity;
    using Microsoft.Graph.Models;
    class Program
    {
        static async Task Main(string[] args)
        {
            
            var clientId = "ClientID";
            var tenantId = "TenantID";
            var clientSecret = "ClientSecret";
    
            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
            var graphClient = new GraphServiceClient(clientSecretCredential);
    
            var userPrincipalName = "rukuser@XXX.onmicrosoft.com";  
            var groupId = "GroupID";  
    
            try
            {
                // Step 1: Retrieve the User by UserPrincipalName
                var user = await graphClient.Users[userPrincipalName].GetAsync();
    
                // Step 2: Create a ReferenceCreate object to specify the user to add
                var requestBody = new ReferenceCreate
                {
                    OdataId = $"https://graph.microsoft.com/v1.0/directoryObjects/{user.Id}"
                };
    
                // Step 3: Add the user to the specified group
                await graphClient.Groups[groupId].Members.Ref.PostAsync(requestBody);
    
                Console.WriteLine("User added to the group successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
    

    enter image description here

    The user added successfully to the Group:

    enter image description here