EWS API,BindToItems上未经授权的401

时间:2020-08-10 09:49:08

标签: c# oauth exchangewebservices unauthorized

我正在努力完成一个简单的任务,该任务在Exchange Online的特定文件夹中获取新电子邮件,设置“已处理”类别,然后存储电子邮件。

首先,我这样创建App权限:

 var app = ConfidentialClientApplicationBuilder.Create(_appConfig.ClientId)
                                                          .WithAuthority(AzureCloudInstance.AzurePublic,
                                                                         _appConfig.Tenant)
                                                          .WithClientSecret(_appConfig.ClientSecret)
                                                          .Build();
            AuthenticationResult authResultresult = null;
            var ewsScopes = new[] {"https://outlook.office.com/.default"};

        
            authResultresult = await app.AcquireTokenForClient(ewsScopes)
                                                     .ExecuteAsync();      

然后我创建Exchange-Client并使用创建的Oauth-Token进行授权:

var result = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
        result.KeepAlive = false;
        result.DateTimePrecision = DateTimePrecision.Milliseconds;
        result.Url =  new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
        result.UseDefaultCredentials = false;         

        var authResultresult = await CreateAppPermissions(_appConfig);
        result.Credentials = new OAuthCredentials(authResultresult.AccessToken);            

此后,我用我的mainSMTP帐户模拟了SMTP用户

result.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, _appConfig.SMTPMailAccount);

之后,我使用此代码使用已知ID检索电子邮件,为其添加新的Category并更新如下项目:

   var itemsToStore = result.BindToItems(new []{newItemId}, props);
                foreach (var itemToStore in itemsToStore)
                {                   
                    itemToStore.Item.Categories.Add("Processed");
                
                    itemToStore.Item.Update(ConflictResolutionMode.AlwaysOverwrite, true); 
                } 

此代码先前已产生“访问被拒绝。检查凭据,然后重试。,无法保存对项目所做的更改以存储。”-Item.Update异常。经过研究,我发现了这一点:

Office 365 API ErrorAccessDenied (Access is denied. Check credentials and try again.)

并遵循建议的解决方案,删除了“具有对用户邮箱的完全访问权限”-复选框标记。

此后,当我调用BindToItems时,我得到401的未授权。 取消复选框是否向后退?

1 个答案:

答案 0 :(得分:0)

已解决: 找到了401的解决方案:

由于我使用的是EWS(也称为Exchange Web Services)旧API,因此删除该复选框是错误的。

“访问被拒绝。检查凭据,然后重试。,“无法保存对项目所做的更改要存储。”是模拟用户无权更改其他人的电子邮件

相关问题