下面是一个使用AAD Graph API进行增量查询的代码示例:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string tenantId = "";
string clientId = "";
string clientSecret = "";
string deltaToken = ""; // 初始增量令牌
using (HttpClient client = new HttpClient())
{
// 获取访问令牌
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken(tenantId, clientId, clientSecret));
// 构建增量查询URL
string requestUrl = $"https://graph.windows.net/{tenantId}/directoryObjects?api-version=1.6&$filter=signInActivity/lastSignInDateTime ge 2022-01-01T00:00:00Z&$deltaToken={deltaToken}";
// 发送增量查询请求
HttpResponseMessage response = await client.GetAsync(requestUrl);
response.EnsureSuccessStatusCode();
// 获取响应内容
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
// 解析响应中的增量令牌
deltaToken = response.Headers.GetValues("odata.deltaLink").FirstOrDefault();
Console.WriteLine(deltaToken);
}
Console.ReadLine();
}
static async Task GetAccessToken(string tenantId, string clientId, string clientSecret)
{
string authority = $"https://login.microsoftonline.com/{tenantId}";
string resource = "https://graph.windows.net";
using (HttpClient client = new HttpClient())
{
var requestParameters = new Dictionary()
{
{ "grant_type", "client_credentials" },
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "resource", resource }
};
var requestContent = new FormUrlEncodedContent(requestParameters);
HttpResponseMessage response = await client.PostAsync($"{authority}/oauth2/token", requestContent);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
var accessToken = JObject.Parse(result)["access_token"].Value();
return accessToken;
}
}
}
在上述示例中,需要替换
,
和
为你自己的租户ID,客户端ID和客户端密钥。
此示例中的增量查询URL中包含了一个过滤器,只返回从2022年1月1日以来有登录活动的目录对象。你可以根据需要修改过滤器条件。
增量查询响应中的增量令牌通过odata.deltaLink
标头返回。你可以使用该令牌来进行后续的增量查询。