我正在使用 Microsoft Graph API 开发 Windows 表单应用程序。有谁知道如何获取访问令牌以及如何创建 GraphServiceClient?
答案 0 :(得分:0)
private async Task<string> GetAccessToken()
{
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(APP_ID)
.WithClientSecret(APP_SECRET)
.WithAuthority($"https://login.microsoftonline.com/{TENANT_ID}")
.WithRedirectUri("https://localhost")
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
return result.AccessToken;
}
private GraphServiceClient GetGraphClient()
{
var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
// get an access token for Graph
var accessToken = GetAccessToken().Result;
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
return Task.FromResult(0);
}));
return graphClient;
}