使用客户端 ID 和客户端机密和图表获取访问令牌以从 Azure 拉取用户组所需的范围 API

Scope needed to get access token to pull user groups from Azure using client id and client secret and graph API

我正在尝试使用我的客户端密码和客户端 ID 在我的 azure 租户中获取组。问题是我不知道在获取访问令牌以使用图形 api 时要传递什么范围。我使用 https://graph.microsoft.com/.default 获取访问令牌,但这不包括拉组的权限。使用什么范围比较合适

https://docs.microsoft.com/en-us/graph/api/group-list?view=graph-rest-1.0#permissions

Permissions

One of the following permissions is required to call this API. To learn more, including how to choose permissions, see Permissions.


Permission type Permissions (from least to most privileged)

Delegated (work or school account) Group.Read.All, Group.ReadWrite.All

Application Group.Read.All, Group.ReadWrite.All

您需要在 AAD 中配置 API 访问权限,而不是范围。请确保您不要忘记点击“授予权限”

示例假定您需要应用程序权限。委托权限的工作方式类似。

使用MSAL进行身份验证获取数据的示例代码:

        IConfidentialClientApplication app = new ConfidentialClientApplication(
            "clientId",
            "https://login.microsoftonline.com/yourtenant.onmicrosoft.com",
            "http://localhost (redirecturi)",
            new ClientCredential("secret"),
            new TokenCache(), new TokenCache());

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

        try
        {
            AuthenticationResult result = await app.AcquireTokenForClientAsync(scopes);
            System.Console.WriteLine(result.AccessToken);

            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
                var groupResponse = await http.GetAsync("https://graph.microsoft.com/v1.0/groups");
                var groupJson = await groupResponse.Content.ReadAsStringAsync();
                System.Console.WriteLine(groupJson);
            }
        }
        catch (Exception ex)
        {
            System.Console.WriteLine(ex.Message);
        }