Microsoft图形API:在尝试读取用户组时获取403

时间:2018-03-25 03:07:59

标签: azure-active-directory microsoft-graph

我正在尝试获取用户登录应用程序的用户组信息。

使用下面的代码,当我点击https://graph.microsoft.com/v1.0/users/{user}时,我能够看到该用户存在(200),但是当我尝试点击https://graph.microsoft.com/v1.0/users/{user}/memberOf时,我得到的是403。

private static async Task Test()
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "TOKEN HERE");

            var user = "testuser@onmicrosoft.com";
            var userExist = await DoesUserExistsAsync(client, user);

            Console.WriteLine($"Does user exists?  {userExist}");

            if (userExist)
            {
                var groups = await GetUserGroupsAsync(client, user);

                foreach (var g in groups)
                {
                    Console.WriteLine($"Group:  {g}");
                }

            }
        }
    }

    private static async Task<bool> DoesUserExistsAsync(HttpClient client, string user)
    {
        var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users/{user}");

        return true;
    }

    private static async Task<string[]> GetUserGroupsAsync(HttpClient client, string user)
    {
        var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users/{user}/memberOf");
        var obj = JsonConvert.DeserializeObject<JObject>(payload);
        var groupDescription = from g in obj["value"]
                               select g["displayName"].Value<string>();

        return groupDescription.ToArray();
    }

这是与权限问题相关的事情,我的令牌现在已经低于范围,

enter image description here

注意 - 在这里,我不是试图访问其他用户/组信息,而只是访问谁登录。谢谢!

1 个答案:

答案 0 :(得分:3)

调用/v1.0/users/[a user]/memberOf要求您的访问令牌包含Directory.Read.All,Directory.ReadWrite.All或Directory.AccessAsUser.All,这是 记录在https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_memberof

在代码中实现之前测试此API调用的一种好方法是使用Microsoft Graph explorer,您可以使用“修改权限”对话框更改令牌所具有的权限。