# 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](https://learn.microsoft.com/en-us/graph/api/user-list-mailfolders?view=graph-rest-1.0\&tabs=http#permissions)

### Using Delegated ROPC Auth

![](https://2627915664-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FC5L8BFhTKgXFngIiQkEm%2Fuploads%2F6jpqol6ghPRti4XIybqI%2Fimage.png?alt=media\&token=2d910f68-ca01-4538-9b8b-fbfb919ac1c1)

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](https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-net-instantiate-public-client-config-options) + addition of redirectURI to json file

```json
{
  "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"
  }
}
```

```csharp
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();
        }*/
    }
}

```

{% file src="<https://2627915664-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FC5L8BFhTKgXFngIiQkEm%2Fuploads%2Fgit-blob-930de5cf23f1043bed179e38a9fd5565b1a3baff%2FModern%20Auth%20Steps.docx?alt=media>" %}
