I am writing an application to communicate with Exchange Online using the EWS Managed API and authenticate my application via OAuth 2.0 utilizing ADAL library.
The access token expires after 60 minutes. After which I need to refresh the access token. Currently, I am doing it in StreamSubscriptionConnection OnNotificationEvent handler, as well as my OnDisconnect event handler to refresh the OAuth access token using the following code.
private void OnNotificationEventHandler(object sender, NotificationEventArgs args)
{
exchangeService.Credentials = new OAuthCredentials(GetOAuthAccessToken().Result);
// Do my work
}
I also added the same refresh access token code in my OnDisconnect event handler since StreamSubscriptionConnection is only kept open for 30 minutes at most.
private void OnDisconnectEventHandler(object sender, SubscriptionErrorEventArgs args)
{
exchangeService.Credentials = new OAuthCredentials(GetOAuthAccessToken().Result);
streamingSubscriptionConnection.Open();
}
Here is the code I have for access token.
private async Task<string> GetOAuthAccessToken(PromptBehavior promptBehavior = PromptBehavior.Auto)
{
var authenticationContext = new AuthenticationContext(myAadTenant);
var authenticationResult = await authenticationContext.AcquireTokenAsync(exchangeOnlineServerName, myClientId, redirectUri, new PlatformParameters(promptBehavior));
return authenticationResult.AccessToken;
}
Even thought the above approach "works", I feel like this isn't the best way of handling the situation because I pretty much need to make sure I refresh my access token whenever I communicate with EWS. If I add another event handler and I forget to add token refresh logic inside the event handler, I could potentially get a 401 while handling that event if my access token expires and yet I need to call EWS in the event handler.
The code above is simplified, I could put try catch whenever I communicate with EWS and if I get 401, I refresh my access token and try again but that doesn't solve the inconvenience I mentioned above.
I think there should be an easier way to handle the problem but I haven't found the right documentations. Here is the material I referred to while doing my development. https://blogs.msdn.microsoft.com/webdav_101/2015/05/11/best-practices-ews-authentication-and-access-issues/