【发布时间】:2022-11-09 07:16:21
【问题描述】:
我正在使用 Microsoft.Graph SDK,我需要在类库中以编程方式获取电子邮件 SentItems。
我正在使用以下代码创建客户端:
private static Graph.GraphServiceClient CreateClient()
{
var scopes = new[] { "User.Read" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "xxx";
// Value from app registration
var clientId = "xxxx";
var pca = Microsoft.Identity.Client.PublicClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.Build();
// DelegateAuthenticationProvider is a simple auth provider implementation
// that allows you to define an async function to retrieve a token
// Alternatively, you can create a class that implements IAuthenticationProvider
// for more complex scenarios
var authProvider = new Graph.DelegateAuthenticationProvider(async (request) =>
{
// Use Microsoft.Identity.Client to retrieve token
var result = await pca.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
return new Graph.GraphServiceClient(authProvider);
}
然后我试图用下一个方式使用客户端:
var sentEmails = graphClient.Users[authMail].MailFolders.SentItems.Request().GetAsync().Result;
但是在执行请求时出现以下异常:
抛出异常:“Microsoft.Identity.Client.MsalUiRequiredException” 在 System.Private.CoreLib.dll 抛出异常: System.Private.CoreLib.dll 中的“System.AggregateException”
我认为另一种选择可能是获取身份验证令牌。我可以使用以下代码获取身份验证令牌:
private static async Task<string> GetGraphToken() { var resource = "https://graph.microsoft.com/"; var instance = "https://login.microsoftonline.com/"; var tenant = "xxx"; var clientID = "xxxx"; var secret = "xxxxx"; var authority = $"{instance}{tenant}"; var authContext = new AuthenticationContext(authority); var credentials = new ClientCredential(clientID, secret); var authResult = authContext.AcquireTokenAsync(resource, credentials).Result; return authResult.AccessToken; }它可以正常工作,但是我不知道如何使用它以编程方式执行 API 请求。
这两种变体中的任何一种对我来说都可以,在第一种情况下摆脱异常,或者在第二种情况下找到使用令牌进行编程 SDK API 调用的方法。
接下来我可以尝试什么?
编辑 1
我正在尝试下一种方法,但抛出了相同的异常:
var accessToken = GetToken(); var client = new Graph.GraphServiceClient( new Graph.DelegateAuthenticationProvider( (requestMessage) => { requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); return Task.FromResult(0); })); var mails = client.Users[authMail].MailFolders.SentItems.Messages.Request().GetAsync().Result;
【问题讨论】:
标签: c# microsoft-graph-api asp.net-core-webapi token