James
James

Reputation: 1261

Executing POST request for Microsoft Graph API to add members to an AD group

I am trying to add members to an AD groups invoking Microsoft Graph API through an Azure Function

It is very easy and straightforward to execute GET requests through Graph API's, but I can't find any examples how I could execute post requests for the Graph API

I do have an example of a post request for the Graph API which is

POST https://graph.microsoft.com/v1.0/groups/{id}/members/$ref
Content-type: application/json
Content-length: 30

{
  "@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/{id}"
}

Here is the code I successfully use to retrieve the Graph response

public static async Task<HttpResponseMessage> GetDirectoryUsers(string graphToken, TraceWriter log, string displayName)
{
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);

    string requestUrl = "https://graph.microsoft.com/v1.0/groups?$top=2&$filter=displayName eq '" + displayName + "'&$expand=Members";
    var request = new HttpRequestMessage(new HttpMethod("GET"), requestUrl);
    var response = await client.SendAsync(request);
    return response;
}

However, I am completely lost how I could execute the request through a C# code within the Azure function to ADD the retrieved users to another AD. How can construct the request URL? How should I handle the odata id within that request URL?

If anyone could help me in any way, I would greatly appreciate it

Upvotes: 3

Views: 12446

Answers (4)

Seiya Su
Seiya Su

Reputation: 1874

A reuse method for add sub-group/member to group(O365 doesn't support add sub-group to group now)

/// <param name="memberId">memberId/sub-group id</param>
public static async Task AddGroupMember1(GraphServiceClient graphClient, string groupId, string memberId)
{ 
     User memberToAdd = new User { Id = memberId };
    //Group memberToAdd= new Group { Id = memberId };
    await graphClient.Groups[groupId].Members.References.Request().AddAsync(memberToAdd); 
}

Upvotes: 1

Md. Abdul Alim
Md. Abdul Alim

Reputation: 689

I'm using graph api for sending email. The code in below

public async Task<dynamic> SendMail(string accessToken, MailWrapper mail)
{
    try
    {
        GraphServiceClient graphClient = SDKHelper.GetMicrosoftAuthenticatedClient(accessToken);
        Message message = await BuildEmailMessage(graphClient, mail);
        await graphClient.Me.SendMail(message, true).Request().PostAsync(CancellationToken.None);
        var response = await graphClient.Me.MailFolders.SentItems.Messages.Request()
                                .OrderBy(sendDateTimeDesc)
                                .Top(1)
                                .GetAsync();
        return await Task.FromResult(response);
    }
    catch (ServiceException ex)
    {
        throw ex;
    }
}

Assembly Microsoft.Graph, Version=1.9.0.0

Upvotes: 0

Maria
Maria

Reputation: 31

That's what worked for me

public void AddUserToGroup(string groupId)
    {
        var requestUri = $"{_graphApiUrl}/v1.0/groups/{groupId}/members/$ref";
        var id = "user_id";

        var OdataId = "@odata.id";
        var ODataValue = $"https://graph.microsoft.com/v1.0/users/{id}";

        var content = $@"{{ ""{OdataId}"": ""{ODataValue}"" }}";

        using (var httpClient = new HttpClient())
        using (var httpRequest = CreateHttpRequest(HttpMethod.Post, requestUri, content))
        {
            var response = httpClient.SendAsync(httpRequest).GetAwaiter().GetResult();
            if (!response.IsSuccessStatusCode)
            {
                var reason = $"Status code: {(int)response.StatusCode}, Reason: {response.StatusCode}";
                throw new Exception(reason);
            }
        }
    }

And important thing was when creating a request to use:

request.Content = new StringContent(content, Encoding.UTF8, "application/json");

it didn't work with:

request.Content = new StringContent(content);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");

Upvotes: 0

James
James

Reputation: 1261

Here is the answer that worked for me

public static async Task<string> AddGroupMember(string accessToken, string groupId, string memberId)
{
    var status = string.Empty;
    try
    {
        string endpoint = "https://graph.microsoft.com/v1.0/groups/" + groupId + "/members/$ref";
        string queryParameter = "";

        // pass body data 
        var keyOdataId = "@odata.id";
        var valueODataId = "https://graph.microsoft.com/v1.0/directoryObjects/" + memberId;

        var values = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>(keyOdataId, valueODataId)
};
        var jsonData = $@"{{ ""{keyOdataId}"": ""{valueODataId}"" }}";
        var body = new StringContent(jsonData, Encoding.UTF8, "application/json");


        using (var client = new HttpClient())
        {
            using (var request = new HttpRequestMessage(HttpMethod.Post, endpoint + queryParameter))
            {
                request.Content = body;
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                using (var response = await client.SendAsync(request))
                {
                    if (response.StatusCode == HttpStatusCode.NoContent)
                        status = "Member added to Group";
                    else
                        status = $"Unable to add Member to Group: {response.StatusCode}";
                }
            }
        }
    }
    catch (Exception ex)
    {
        status = $"Error adding Member to Group: {ex.Message}";
    }

    return status;
}

Upvotes: 1

Related Questions