Narendran
Narendran

Reputation: 21

Microsoft EWS throws "403 Forbidden" in modern oAuth implementation c# - Reading mail from outlook

We had implemented modern OAuth implementation for reading mails from outlook mail boxes. The code we used is whatever is available on the microsoft offical website. But it throws "The request failed. The remote server returned an error: (403) Forbidden." . But the authentication token is getting correctly. Here is my code

      static void Main(string[] args)
        {
            MainTask().Wait();
        }

        static async System.Threading.Tasks.Task MainTask()
        {
            // Using Microsoft.Identity.Client 4.22.0
            var cca = ConfidentialClientApplicationBuilder
                .Create(ConfigurationManager.AppSettings["appId"])
                .WithClientSecret(ConfigurationManager.AppSettings["clientSecret"])
                .WithTenantId(ConfigurationManager.AppSettings["tenantId"])
                .Build();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var ewsScopes = new string[] { "https://outlook.office365.com/.default" };

            try
            {
                var authResult = await cca.AcquireTokenForClient(ewsScopes)
                    .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, "[email protected]");
                
                

                //Include x-anchormailbox header
                ewsClient.HttpHeaders.Add("X-AnchorMailbox", "[email protected]");

                // Make an EWS call
                var folders = ewsClient.FindFolders(WellKnownFolderName.Inbox, new FolderView(10));
                foreach (var folder in folders)
                {
                    Console.WriteLine($"Folder: {folder.DisplayName}");
                }
            }
            catch (MsalException ex)
            {
                Console.WriteLine($"Error acquiring access token: {ex}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex}");
            }

            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine("Hit any key to exit...");
                Console.ReadKey();
            }
        }

Almost we tried all possible ways. Please anyone support who already successfully implemented this modern OAuth functionality. Thanks in advance

Upvotes: 2

Views: 3233

Answers (2)

madmonk46
madmonk46

Reputation: 499

Checking some documentation for the definition of 403 (Forbidden) will reveal the key difference between it and 401 (Unauthorised), namely that 403 relates to a user not having sufficient permissions to access a resource. This means that, while you may have a valid authentication token, that token does not grant you access to the specific resource you're requesting. You should check the permissions of the user you're authenticating as.

Upvotes: 1

Rau18
Rau18

Reputation: 91

Try to grant "full_access_as_app" on AAD, you will have to grant admin permission and then try to execute the code.

Check the next post and see if it helps: Error 403: Forbidden when I try to connect to server OAuth 2.0

Upvotes: 4

Related Questions