Forum Discussion
woelki
Aug 26, 2022Iron Contributor
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 ...
woelki
Aug 30, 2022Iron 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: