即使正在生成令牌,Microsoft.Exchange.WebServices 版本 2.2.1.0 的代码也无法正常工作

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

我的开发环境如下

  • Visual Studio 2022 .net 版本 4.8
  • Microsoft.Exchange.WebServices 版本 2.2.1.0
  • Microsoft.Exchange.WebServices.Auth 版本 15.0.0.0
  • Microsoft.Identity.Client 版本 4.63.0.0 我也有 Azure 权限,如下所示 enter image description here

我在下面编写了生成令牌的代码,但是当它到达该行时

var folders = _service.FindFolders(WellKnownFolderName.Inbox, new FolderView(10));

它会抛出类似

Microsoft.Exchange.WebServices.Data.ServiceRequestException: 'The request failed. The remote server returned an error: (403) Forbidden.'
的错误 以下是完整代码

private static void ReadMailsFromExchangeServer()
{
    //  _service.Credentials = new WebCredentials("[email protected]", "qwerty", "tng");
    try
    {

        string token = GetAccessToken();

        ExchangeService _service = new ExchangeService(ExchangeVersion.Exchange2016)
        {
            Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"),
            Credentials = new OAuthCredentials(token),
        }; // Use your EWS endpoint


        // Impersonate the user you want to act on behalf of
        _service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");
        // Set X-AnchorMailbox header to the SMTP address of the mailbox being accessed
        _service.HttpHeaders.Add("X-AnchorMailbox", "[email protected]");//[email protected]
        _service.HttpHeaders.Add("X-PreferServerAffinity", "true");
        var folders = _service.FindFolders(WellKnownFolderName.Inbox, new FolderView(10));
        foreach (var folder in folders)
        {
            Console.WriteLine(folder.DisplayName);
        }

    }
    catch (Exception ex)
    {

    }
}
        private static async void GetTokens()
        {
            // Using Microsoft.Identity.Client 4.22.0
            var cca = ConfidentialClientApplicationBuilder
                .Create(ConfigurationManager.AppSettings["appId"])
                .WithClientSecret(ConfigurationManager.AppSettings["clientSecret"])
                .WithTenantId(ConfigurationManager.AppSettings["tenantId"])
                .Build();

            var ewsScopes = new string[] { "https://outlook.office365.com/.default" };

            try
            {
                var authResult = await cca.AcquireTokenForClient(ewsScopes)
                    .ExecuteAsync();
                var ewsClient = new ExchangeService();
                ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
                ewsClient.ImpersonatedUserId =
                   new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");

                //Include x-anchormailbox header
                ewsClient.HttpHeaders.Add("X-AnchorMailbox", "[email protected]");


            }
            catch (Exception ex)
            {

            }
        }
c# azure console-application exchangewebservices .net-4.8
1个回答
0
投票

最初,当授予与您相同的权限时,我遇到了相同的错误

enter image description here

错误“请求失败。远程服务器返回错误:(403) 禁止”通常发生在应用程序没有执行该操作所需的权限时。

因此,要解决该错误,您需要向 Microsoft Entra ID 应用程序授予 Office 365 Exchange Online

full_access_as_app
应用程序类型 API 权限,如下所示:

enter image description here

授予所需的 API 权限后,我能够成功获取文件夹

namespace EWSIntegration
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            await ReadMailsFromExchangeServer();
        }

        private static async System.Threading.Tasks.Task ReadMailsFromExchangeServer()
        {
            try
            {
                string token = await GetAccessToken();

                ExchangeService _service = new ExchangeService(ExchangeVersion.Exchange2016)
                {
                    Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"),
                    Credentials = new OAuthCredentials(token),
                };


                // Impersonate the user you want to act on behalf of
                _service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "test @test.com");
                // Set X-AnchorMailbox header to the SMTP address of the mailbox being accessed
                _service.HttpHeaders.Add("X-AnchorMailbox", "test @test.com");
                _service.HttpHeaders.Add("X-PreferServerAffinity", "true");
                var folders = _service.FindFolders(WellKnownFolderName.Inbox, new FolderView(10));
                foreach (var folder in folders)
                {
                    Console.WriteLine($"Folder: {folder.DisplayName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }

                private static async Task<string> GetAccessToken()
        {
            string clientId = "ClientID";
            string clientSecret = "ClientSecret"; 
            string tenantId = "TenantID"; 

            try
            {
                var cca = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithTenantId(tenantId)
                .Build();
                var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
                var authResult = await cca.AcquireTokenForClient(ewsScopes).ExecuteAsync();
                return authResult.AccessToken;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred while acquiring the token: {ex.Message}");
                throw;
            }
        }
    }
}

enter image description here

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