Search code examples
c#azureoffice365exchangewebservicesazure-ad-msal

Get delegate permission in MSAL for EWS without PublicClientApplicationBuilder and AcquireTokenInteractive


In EWS OAuth flow we can get delegate permissions by following:

var pcaOptions = new PublicClientApplicationOptions
{
    ClientId = ConfigurationManager.AppSettings["appId"],
    TenantId = ConfigurationManager.AppSettings["tenantId"]
};

var pca = PublicClientApplicationBuilder
    .CreateWithApplicationOptions(pcaOptions).Build();

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

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

Above code opens the dialog for putting in Username/Password.

Is there any way I can bypass the dialog and request token by providing credentials in code itself, but with delegated permissions only


Solution

  • Yes what you talking about is ROPC https://learn.microsoft.com/en-us/azure/active-directory//develop/v2-oauth-ropc . Using credentials this way is generally discouraged because of the trust issue around handling credentials directly. The one thing you need to ensure is in that in your application registration you have

    Treat application as a public client.

    Select in the Authentication tag (it down the very bottom)

    For the code look at https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Username-Password-Authentication eg

    NetworkCredential Credentials =  new NetworkCredential(UserName,Password); 
    pca.AcquireTokenByUsernamePassword(ewsScopes,Credentials.UserName, Credentials.SecurePassword).ExecuteAsync();
    

    If your looking for a more secure way consider using Managed Identities https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview