使用Rest(400)错误请求将Azure AD用户添加到组

时间:2016-09-08 12:17:07

标签: c# visual-studio rest azure sharepoint

我是休息的新手,我正在尝试将Azure广告用户添加到特定群组,我收到了错误的请求,任何人都可以帮我看看我做错了什么......

我的代码是:

        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);
        try
        {

            using (var streamWriter = new StreamWriter(endpointRequest.GetRequestStream()))
            {
                streamWriter.Write(ans);
                streamWriter.Flush();
                streamWriter.Close();
            }

            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)
        {
            Console.WriteLine(ex.Message);
        }

变量serviceRootUrl是“https://graph.windows.net/ {organization} /”

我得到的错误是远程服务器返回错误:(400)错误请求。

1 个答案:

答案 0 :(得分:0)

我已经测试过在fiddler中使用Azure图形API将用户添加到AD组。

方法:POST

网址:https://graph.windows.net/myorganization/groups/cd2ddafa-d141-4b66-84ba-8673844efca5/ $ links / members?api-version = 1.6
//上面链接中的guid是组对象ID,我们可以在Azure门户中找到它,如下面的屏幕截图。

enter image description here

这是我的标题:

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

邮政机构:

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

//我们也可以在azure portal中找到用户guid。 enter image description here

通过上述帖子请求,我将该成员添加到该组: enter image description here

请运行您的代码并使用fiddler捕获流量,然后检查您的标题,网址,帖子正文以确保没有问题。您还可以阅读this article,了解有关如何通过图API将用户添加到群组的更多详细信息。