我正在尝试通过Azure AD使用EWS托管Api和Office 365 Api。到目前为止,我已经完成了以下任务。
这里是我所关注的博客的链接: http://www.jeremythake.com/2014/08/using-the-exchange-online-ews-api-with-office-365-api-via-azure-ad/#comment-280653
我的控制器中的代码:
var outlookClient = await AuthHelper.EnsureOutlookServicesClientCreatedAsync("Mail");
IPagedCollection<IMessage> messagesResults = await outlookClient.Me.Messages.ExecuteAsync();
string messageId = messagesResults.CurrentPage[0].Id;
string tokenx = AuthHelper.GetSessionToken();
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.HttpHeaders.Add("Authorization", "Bearer " + tokenx);
service.PreAuthenticate = true;
service.SendClientLatencies = true;
service.EnableScpLookup = false;
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ExFolder rootfolder = ExFolder.Bind(service, WellKnownFolderName.MsgFolderRoot);
已编辑:我成功获取accessToken并使用它来对EWS托管的Api进行调用,但它失败了403:Forbidden异常。我们将非常感谢您的帮助。
最好的问候,
答案 0 :(得分:3)
我检查了EWS跟踪,我了解到EWS抱怨无效令牌和权限不足。我将我的应用程序重新注册到Azure AD并启用了对邮箱的完全访问权限。
我评论了以下代码。
//var outlookClient = await AuthHelper.EnsureOutlookServicesClientCreatedAsync("Mail");
//try
//{
// IPagedCollection<IMessage> messagesResults = await outlookClient.Me.Messages.ExecuteAsync();
// string messageId = messagesResults.CurrentPage[0].Id;
//}
//catch
//{
// System.Diagnostics.Debug.WriteLine("Something bad happened. !!");
//}
我从以下链接示例获取访问令牌。 https://github.com/OfficeDev/Office-365-APIs-Starter-Project-for-ASPNETMVC
以下是完成身份验证主要任务的完整控制器代码。
string resourceUri = "https://outlook.office365.com";
var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Settings.Authority, new NaiveSessionCache(signInUserId));
string tokenx = await AuthHelper.AcquireTokenAsync(authContext, resourceUri, Settings.ClientId, new UserIdentifier(userObjectId,UserIdentifierType.UniqueId));
System.Diagnostics.Debug.WriteLine("Token:" + tokenx);
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.TraceListener = new EwsTrace();
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.HttpHeaders.Add("Authorization", "Bearer " + tokenx);
service.PreAuthenticate = true;
service.SendClientLatencies = true;
service.EnableScpLookup = false;
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ExFolder rootfolder = ExFolder.Bind(service, WellKnownFolderName.MsgFolderRoot);
Console.WriteLine("The " + rootfolder.DisplayName + " has " + rootfolder.ChildFolderCount + " child folders.");
我注意到的重要一点是,我无法使用相同的令牌来访问office365 api和EWS托管的Api,因为EWS可以使用完全邮箱访问,而office365则不然。我请求开发人员确认这一点,也许我做错了,但我的问题现在已经解决了。
答案 1 :(得分:1)