The given token is invalid error in EWS OAuth authentication when using personal account

Antony Raj M 1 Reputation point
2022-07-06T18:18:48.977+00:00

I have to get the contacts from Exchange server from any account, so we have used the code from below link.

https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth

But it is not working for personal accounts, which is working fine for our organization account. So I have used AadAuthorityAudience property instead of TenantId and changed the scope from EWS.AccessAsUser.All to others. Now authentication got success but getting "The given token is invalid" error while using the token in ExchangeService.

var pcaOptions = new PublicClientApplicationOptions {  
    ClientId = "77xxxxxxxxxxx92324",  
    //TenantId = "7887xxxxxxxxxxxxx14",  
    RedirectUri = "https://login.live.com/oauth20_desktop.srf",  
    AadAuthorityAudience = AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount};  
  
var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(pcaOptions).Build();  
  
//var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" };  
var ewsScopes = new string[] { "User.Read", "Contacts.ReadWrite.Shared" };  
  
var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();  
  
var ewsClient = new ExchangeService();  
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");  
//ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "axxx@xxxx.net");  
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);  
  
// Make an EWS call  
var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));  
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
35,028 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Alfredo Revilla (MSFT) 26,756 Reputation points
    2022-07-06T22:49:00.79+00:00

    Hello @Antony Raj M , https://outlook.office365.com/EWS.AccessAsUser.All is the right scope to use. The scope is invalid for personal accounts since they're not supported by EWS.

    Let us know if this answer was helpful to you or if you need additional assistance. If it was helpful, please remember to accept it and complete the quality survey so that others in the community with similar questions can more easily find a rated solution.