C#/VB code Auth

The security team will need to determine which scenario to go with: delegated or app-only. The recommendation is of course to use the technology that is designed to work specifically for most contexts: app only. However, this is totally up to case by case.

  • If a delegated scenario is desired, the redirect URI must be reconfigured. Additionally, if an ROPC flow is desired (Microsoft highly recommend AGAINST using the ROPC flow if possible), then the app registration will also need to be set to allow Public Client Flows in the ‘Authentication Tab’ of the App Registration

  • If an app-only scenario is desired, then the proper app-only permissions must be granted to the app registration: List mailFolders - Microsoft Graph v1.0 | Microsoft Learn

Using Delegated ROPC Auth

With the above app registration settings, teams managed to set up the auth using Instantiate a public client app (MSAL.NET) - Microsoft Entra | Microsoft Learn + addition of redirectURI to json file

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "SwaggerConfiguration": {
    "Title": "xxxxx Email Reader Service",
    "Version": "V3.0.4",
    "Description": "Reads incoming xxx emails from customers and assigns them",
    "TermsOfService": "https://www.jibal.com/about-us/our-core-values/the-jibal-code/privacy.html",
    "ContactName": "xxxxx",
    "ContactEmail": "xxxxx@jibal.com",
    "LicenseName": "Use in Jibal",
    "LicenseUrl": "https://opensource.org/licenses/MIT"
  },
  "DataBaseContextSQL": {
    //STG
    //"connectionString": "Host=rdsdb-xxxxx.us-east-1.rds.amazonaws.com;Port=5432;Username=xxxxx;Password=xxxxx;Database=xxxxx;"
    //PRD
    "connectionString": "Host=rds-xxxxx.us-east-1.rds.amazonaws.com;Port=5432;Username=xxxxx;Password=xxxxx;Database=xxxxx;"

  },
  "Authentication": {
    "AzureCloudInstance": "AzurePublic",
    "ClientId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "TenantId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "RedirectUri":  "http://localhost"
  },

  "WebAPI": {
    "MicrosoftGraphBaseEndpoint": "https://graph.microsoft.com"
  }
}
public async Task<ExchangeService> ConnectToEmailAsync(CtSites site)
        {
            _logger.LogInfo("SITE DATA: " + site.SiteName);
            try
            {



                var ewsClient = new ExchangeService();

                SampleConfiguration config = SampleConfiguration.ReadFromJsonFile("appsettings.json");
                var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(config.PublicClientApplicationOptions)
                           .Build();

                

       

                    // The permission scope required for EWS access
                    var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" };

                    try
                    {
                    // Make the interactive token request
                    var authResult = await app.AcquireTokenInteractive(ewsScopes).ExecuteAsync(); 

                        // Configure the ExchangeService with the access token
                        
                        ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                        ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);

                        // Make an EWS call
                        var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(40));
                        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();
                       
                    }

                return ewsClient;
            }
            catch (Exception ex)
            {
                _logger.LogError("Connection to " + site.SiteName + " fails. No connection to the email, please veirfy User and Passwrod: " + site.EmailAccount);
                _saveLogs.SaveLogError(ex, MethodBase.GetCurrentMethod().Name, site.PksiteId);
                return new ExchangeService();
            }
        }

       /* ExchangeService IConnectToEmailService.ConnectToEmailAsync(CtSites site)
        {



            throw new NotImplementedException();
        }*/
    }
}

Last updated