c# - 在守护程序中使用 Microsoft Graph API
问题描述
我正在尝试编写一个使用 Graph API 将项目填充到共享 Outlook 日历中的守护程序。我在apps.dev.microsoft.com 上创建了一个应用程序,赋予它图形权限(Delegated User.Read、Directory.Read.All、User.Read.All)和应用程序权限(Calendars.ReadWrite、Directory.Read.All、 User.Read.All),并生成一个秘密。
我们的 Azure 管理员已完成管理员同意流程,并确认已创建 AAD ServicePrincipal。
在以下代码中,创建了 graphClient,但是当我尝试使用它(在此处列出用户)时,我得到异常 Authorization_IdentityNotFound,“无法建立调用应用程序的身份”。我错过了什么?
我在交互式身份验证流程示例中成功使用了相同的 clientID,因此 AAD 中的应用程序设置似乎没问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Graph;
using System.Net.Http.Headers;
namespace CCSync
{
class Program
{
private static string ClientId = "e914fd5d-xxx-xxxx-xxxx-xxxxxxxxxxxx";
private static string ClientSecret = "...";
private static GraphServiceClient graphClient = null;
static async Task Main(string[] args)
{
IGraphServiceUsersCollectionPage users = await GetUsersAsync();
}
public static async Task<IGraphServiceUsersCollectionPage> GetUsersAsync()
{
var graphClient = GetGraphClient();
try
{
var group = await graphClient.Users.Request().GetAsync();
if (group == null) return null;
return group;
}
catch (ServiceException e)
{
Console.WriteLine(e.Message);
return null;
}
}
private static GraphServiceClient GetGraphClient()
{
// get access token including application permissions
ConfidentialClientApplication cl = new ConfidentialClientApplication(
ClientId,
"https://login.microsoftonline.com/mytenant.onmicrosoft.com/oauth2/v2.0/token",
new ClientCredential(ClientSecret),
new TokenCache(), null);
AuthenticationResult authResult = cl.AcquireTokenForClientAsync(
new string[] { "https://graph.microsoft.com/.default" }).Result;
if (graphClient == null)
{
// Create Microsoft Graph client.
try
{
graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = authResult.AccessToken;
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
return graphClient;
}
catch (Exception ex)
{
Console.WriteLine("Could not create a graph client: " + ex.Message);
return null;
}
}
else
{ return graphClient; }
}
}
}
解决方案
推荐阅读
- maven - 如何将 Maven 项目模块中的所有依赖项复制到目录中?
- jquery - 控制器将微软图表作为图像返回给 AJAX 调用
- c# - QuickFixN 不发送交易时段的登录信息
- c# - 在 C#.Net 中将文件上传到 zoho 联系人
- batch-file - 只允许数组窗口批处理文件中的唯一条目
- sqlite - 如何使用 FTS3 优化加入(在文本上)
- kubernetes - kube-state-metrics - 无法列出 *v1.Pod: text/html 的序列化程序;charset=utf-8 不存在
- javascript - 如何仅为 IE 9 以上的浏览器插入脚本
- c# - 如何为多项目 Nuget 包创建符号?
- javascript - JSPDF:未捕获的类型错误:无法读取未定义的属性“长度”