Did you grant impersonation permissions? full_access_as_app is needed for this scenario. In addition, access might be blocked due to application access policy, as detailed for example here: https://practical365.com/new-application-access-policies-extend-support-for-more-scenarios/
Getting a 403 Forbidden error message when trying to access Exchange folders via using ConfidentialClientApplicationBuilder Build()
Paul_S_
1
Reputation point
Getting the following error:
Error: The request failed. The remote server returned an error: (403) Forbidden.
Error is being triggered on the following call:
var folders = ewsClient.FindFolders(WellKnownFolderName.Inbox, new FolderView(10));
Block of code getting executed:
public static async System.Threading.Tasks.Task processAccountsExchange()
{
try
{
var cca = ConfidentialClientApplicationBuilder
.Create("b3d*********")
.WithClientSecret("P5R******")
.WithTenantId("090********")
.Build();
// The permission scope required for EWS access
var scopes = new string[] { "https://outlook.office365.com/.default" };
//Make the token request
var authResult = await cca.AcquireTokenForClient(scopes).ExecuteAsync();
// Configure the ExchangeService with the access token
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "******@ourcompanydomain.com");
//Include x-anchormailbox header
ewsClient.HttpHeaders.Add("X-AnchorMailbox", "******@ourcompanydomain.com");
var folders = ewsClient.FindFolders(WellKnownFolderName.Inbox, new FolderView(10));
foreach (var folder in folders)
{
Console.WriteLine(folder.WellKnownFolderName.ToString());
}
}
catch (MsalException ex)
{
Console.WriteLine("Error acquiring access token: " + ex.Message.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message.ToString());
}
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Hit any key to exit...");
Console.ReadKey();
}
}
Exchange | Exchange Server | Development
586 questions
Exchange | Exchange Server | Management
7,920 questions
1 answer
Sort by: Most helpful
-
Vasil Michev 119.5K Reputation points MVP Volunteer Moderator
2022-12-03T08:13:14.133+00:00