jvr jvr - 5 months ago 50
reST (reStructuredText) Question

Adding a Azure AD User to a group using Rest (400) Bad Request

I am new with rest and I'm trying to Add a Azure Ad User to a specific group and I get bad request, can anyone help me see what I'm doing wrong...

My code is this:

var queryString = HttpUtility.ParseQueryString(string.Empty);

// Specify values for the following required parameters
queryString["api-version"] = "1.6";
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
ClientCredential clientCred = new ClientCredential(clientID, clientSecret);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resAzureGraphAPI, clientCred);
// Specify values for path parameters (shown as {...})
var uri = serviceRootURL + "/groups/" + "software developer" +"/$links/members" + "?" + queryString;

HttpWebRequest endpointRequest = (HttpWebRequest)WebRequest.Create(uri);
endpointRequest.Method = "POST";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", "Bearer " + authenticationResult.AccessToken);
endpointRequest.ContentType = "application/json";
Dictionary<string, object> dataFrmDb = new Dictionary<string, object>();
dataFrmDb.Add("url", serviceRootURL + "/users/" + userPrincipalName);

string ans = JsonConvert.SerializeObject(dataFrmDb);

using (var streamWriter = new StreamWriter(endpointRequest.GetRequestStream()))

HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
using (var streamReader = new StreamReader(endpointResponse.GetResponseStream()))
var result = streamReader.ReadToEnd();
Console.WriteLine(endpointResponse.StatusCode.ToString() + ":" + result);
catch (Exception ex)

where the variable serviceRootUrl is "https://graph.windows.net/{organization}/"

the error I get is The remote server returned an error: (400) Bad Request.


I have tested to add user to AD group using Azure graph API in fiddler.

Method: POST

URL: https://graph.windows.net/myorganization/groups/cd2ddafa-d141-4b66-84ba-8673844efca5/$links/members?api-version=1.6
//guid in above link is group object ID, we could find it in Azure portal like following screenshot.

enter image description here

Here is my headers:

User-Agent: Fiddler
Host: graph.windows.net
Content-Type: application/json
Content-Length: 111
Authorization: Bearer <your token>

Post Body:

  "url": "https://graph.windows.net/myorganization/directoryObjects/fe989a2b-81d1-48ca-aa15-0ac52688f65b"

// we could also find the user guid in azure portal too. enter image description here

With above post request, I add the member to the group: enter image description here

Please run your code and use fiddler to capture the traffic, then check your headers, url, post body to ensure there is no issues. You could also read this article for more details about how to add user to a group via graph API.