访问图API时访问令牌问题

时间:2016-11-21 09:19:53

标签: c# azure-ad-graph-api

我使用下面的代码使用图形API从azure AD中获取用户,但不知怎的,我在这样做时遇到了令牌访问问题。

static async void MakeRequest()
        {
            var client = new HttpClient();

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

            /* OAuth2 is required to access this API. For more information visit:
               https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks */



            // Specify values for the following required parameters
            queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            // var uri = "https://graph.windows.net/microsoft.onmicrosoft.com/users/{v-sidmis@microsoft.com}?" + queryString;

            var uri = "https://graph.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/users?api-version=1.6";

            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }


        }

此代码来自TechNet。

1 个答案:

答案 0 :(得分:3)

这取决于您想要获取令牌的方式。有很多方案可以将应用程序与Azure AD集成。您可以从here引用它。

例如,如果要在守护程序或服务应用程序中使用Azure AD Graph,我们可以使用客户端凭据流

1。首先,我们需要在portal上注册一个Web应用程序(详细步骤参考here)并授予读取目录数据的权限,如下图所示: enter image description here

2。然后我们可以从门户网站获取 clientId secret tenantId ,并使用以下代码获取令牌(需要安装{{ 3}})

string authority = "https://login.microsoftonline.com/{tenantId}";
string clientId = "";
string secret = "";
string resrouce = "https://graph.windows.net";

var credential = new ClientCredential(clientId, secret);
AuthenticationContext authContext = new AuthenticationContext(authority);

var token = authContext.AcquireTokenAsync(resrouce, credential).Result.AccessToken;

Console.WriteLine(token);  

3。然后我们可以使用此令牌直接调用Azure AD Graph REST,或者我们可以使用Active Directory Authentication Library来检索用户。以下是供您参考的代码示例:

//use the Azure AD client library
string accessToken = "";
string tenantId = ""; 
string graphResourceId = "https://graph.windows.net";

Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);

ActiveDirectoryClient client = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));

foreach(var user in client.Users.ExecuteAsync().Result.CurrentPage)
            Console.WriteLine(user.DisplayName);

//using the HTTP request 
var client = new HttpClient();
var tenantId = "";
var uri = $"https://graph.windows.net/{tenantId}/users?api-version=1.6";
var token = "";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", token);
var response = client.GetAsync(uri).Result;
var result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);

更新

创建应用程序时,Web应用程序/ Web API可以使用保密。然后你可以通过键部分生成键,如下图所示。保存应用程序后,您可以立即复制分泌物。 graph client library for Azure AD