注意:您需要使用 Microsoft.Graph
引用您的项目
首先,您需要一个函数来请求访问令牌
async Task<string> Post(string uri, Dictionary<string, string> parameters)
{
HttpResponseMessage response = null;
try
{
using (var httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) })
{
response = await httpClient.PostAsync(uri, new FormUrlEncodedContent(parameters));
if (!response.IsSuccessStatusCode)
throw new Exception("post request failed.");
var content = response.Content.ReadAsStringAsync().Result;
if (string.IsNullOrWhiteSpace(content))
throw new Exception("empty response received.");
return content;
}
}
catch (Exception e)
{
throw new Exception(error);
}
}
那么你需要一个模型来处理来自网络请求的响应
public class TokenRequest
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
然后你需要一个函数来从网络请求中提取数据
TokenRequest GetAccessToken()
{
// request for access token.
var parameters = new Dictionary<string, string>();
parameters.Add("client_id", "YOUR CLIENT ID");
parameters.Add("client_secret", "YOUR CLIENT SECRET");
parameters.Add("scope", "https://graph.microsoft.com/.default");
parameters.Add("grant_type", "client_credentials");
var response = Post(
$"https://login.microsoftonline.com/{YOUR TENANT ID}/oauth2/v2.0/token",
parameters).Result;
return JsonConvert.DeserializeObject<TokenRequest>(response);
}
然后请求一个经过身份验证的图形 api 客户端
GraphServiceClient GetClient()
{
var tokenRequest = GetAccessToken();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) => {
await Task.Run(() => {
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(
tokenRequest.TokenType,
tokenRequest.AccessToken);
requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\"");
});
}));
return graphClient;
}
然后使用客户端,您现在可以执行查询
var graphClient = GetClient();
var user = await graphClient
.Users["SOME EMAIL ADDRESS HERE"]
.Request()
.GetAsync();
非常重要:您还必须确保您对 Active Directory 应用程序注册具有适当的 api 权限。没有它,你只会得到来自 graph api 的 request denied 响应。
希望这会有所帮助。