如何在 C# 控制台应用程序中使用访问令牌使用具有委托权限的 Microsoft graph api 读取用户电子邮箱?

问题描述 投票:0回答:1

我正在使用 Graph api 通过访问令牌获取用户的邮箱,但收到以下错误消息。

{ “错误”: { “代码”:“错误访问被拒绝”, "message": "访问被拒绝。请检查凭据并重试。", } }

请帮助我解决上述错误。非常感谢任何帮助!!

我正在使用 Mail.Read 委托权限并获取访问令牌来读取用户邮箱

c# .net azure window console-application
1个回答
0
投票

请注意,您可以使用 Mail.Read 委派权限

读取登录用户和共享邮箱。

当我尝试通过在Graph Explorer中执行此查询来读取用户的邮箱时,我也遇到了相同的错误,如下所示:

GET https://graph.microsoft.com/v1.0/users/[email protected]/messages

回复:

enter image description here

要通过 Microsoft Graph API 读取任何用户的邮箱,您需要授予

Mail.Read
Application 类型的权限并切换到 client 凭证 流程。

我注册了一个 Azure AD 应用程序并授予了

Mail.Read
Application 类型的权限,如下所示:

enter image description here

当我在 C# 控制台应用程序中运行下面的代码时,我成功地得到了 response,如下所示:

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models.ODataErrors;

var scopes = new[] { "https://graph.microsoft.com/.default" };

var clientId = "appId";
var tenantId = "tenantId";
var clientSecret = "secret";

var options = new ClientSecretCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};

var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

try
{
    var messages = await graphClient.Users["[email protected]"].Messages.GetAsync();
    foreach (var message in messages.Value)
    {
        Console.WriteLine(message.Subject);
        Console.WriteLine();
    }
}

catch (ODataError odataError)
{
    Console.WriteLine(odataError.Error.Code);
    Console.WriteLine(odataError.Error.Message);
}

回复:

enter image description here

参考: 列出消息 - Microsoft Graph

© www.soinside.com 2019 - 2024. All rights reserved.