我正在尝试使用oauth访问EWS托管API(订阅推送通知),如下所示:
var authenticationTask = await authenticationContext.AcquireTokenAsync("https://outlook.office365.com", new ClientCredential(clientID, clientSecret));
string targetSmtp = "user123@mydomain.onmicrosoft.com";
ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2013);
exchangeService.Url = someURL;
exchangeService.TraceEnabled = true;
exchangeService.TraceFlags = TraceFlags.All;
exchangeService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, "user123@mydomain.onmicrosoft.com");
exchangeService.HttpHeaders.Add("X-AnchorMailbox", targetSmtp);
exchangeService.Credentials = new OAuthCredentials(authenticationTask.AccessToken);
PushSubscription subscription = exchangeService.SubscribeToPushNotifications(
new[] { someFolder },
new Uri(postBackUrl),
15,
null,
EventType.NewMail,
EventType.Created,
EventType.Deleted,
EventType.Modified,
EventType.Moved,
EventType.Copied);
我可以获取我的应用的令牌,但在订阅用户(user123@mydomain.onmicrosoft.com)进行推送通知时,我收到"The request failed. The remote server returned an error: (401) Unauthorized."
错误
更新:尝试遵循此处提到的完全相同的步骤:Azure AD app-only access tokens for exchange impersonation但仍然获得401。
答案 0 :(得分:3)
对于那些在同一问题上苦苦挣扎的人,我们需要使用证书(而不是使用客户端密钥)来获取已注册应用的访问令牌。有关如何操作的详细信息,请参阅:https://blogs.msdn.microsoft.com/exchangedev/2015/01/21/building-daemon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow/