Forum Discussion

woelki's avatar
woelki
Iron Contributor
Aug 26, 2022

Updating unattended EWS scripts using modern auth

Hi there,

a lot of possibilities about phasing out legacy authentication have been discussed here. But I still have a lack of information or let's say I want to find the most comfortable and most secure possibility for my customers.


https://docs.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2?view=exchange-ps

 

But if your scripts contain EWS connections you have to initialize a different way of authentication.

So I found the following option using MSAL, unfortunately this does not work in unattended mode.

https://morgantechspace.com/2022/03/connect-ews-api-with-modern-authentication-using-powershell.html 

And then there is the possibility using the secure application model.

https://docs.microsoft.com/en-us/powershell/partnercenter/multi-factor-auth?view=partnercenterps-3.0#secure-application-model 

I got this working now, the creation of the token for the first time has to be done interactively and the token only lasts for 90 days. I read the hint for securely saving the token to the Azure KeyVault, but how do I do this and how can I re-call this token? Is there even a better way of refreshing the token manually?

Is this now the new go-to solution for unattended EWS scripts, or do you have a even better solution?

1 Reply

  • woelki's avatar
    woelki
    Iron Contributor

    OK, like I have discovered, the PartnerAccessToken does not really work for EWS. It seems the only possibility is to use the Get-MsalToken. But in first line it is interactive.
    How can I get it turn to unattended?

     

    # Provide your Office 365 Tenant Id or Tenant Domain Name
    $TenantId = "contoso.onmicrosoft.com"
        
    # Provide Azure AD Application (client) Id of your app.
    # You should have configured the Delegated permission "EWS.AccessAsUser.All" in the app.
    $AppClientId="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  
     
    $MsalParams = @{
        ClientId = $AppClientId
        TenantId = $TenantId   
        Scopes   = "https://outlook.office.com/EWS.AccessAsUser.All"   
    }
     
    $MsalResponse = Get-MsalToken @MsalParams
    $EWSAccessToken  = $MsalResponse.AccessToken
    
    Import-Module 'C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll'
     
    # Proivde the mailbox id
    $MailboxName ="email address removed for privacy reasons"
     
    $Service = [Microsoft.Exchange.WebServices.Data.ExchangeService]::new()
     
    # Use Modern Authentication
    $Service.Credentials = [Microsoft.Exchange.WebServices.Data.OAuthCredentials]$EWSAccessToken
     
    # Check EWS connection
    $Service.Url = "https://outlook.office365.com/EWS/Exchange.asmx"
    $Service.AutodiscoverUrl($MailboxName,{$true})
    # EWS connection is Success if no error returned.

    What I have done now:

Resources