Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save poiriersimon/af78998383df27ffeabdcd771284c708 to your computer and use it in GitHub Desktop.
Save poiriersimon/af78998383df27ffeabdcd771284c708 to your computer and use it in GitHub Desktop.
Exchange Online EWS with Certificate Authentication
#For this example you need an Azure App registered with a Self Sign Cert and a user with EWS Access to grab email.
#You need AzureAD Module (Save-Module AzureAD -Path C:\temp)
#You need EWS API 2.2 (www.microsoft.com/en-us/download/details.aspx?id=35371)
#App need to have Office 365 API access to read email.
# Permission under Office 365 Exchange Online:
# Admin : Use Exchange Web Services with full access to all mailboxes
# Delegate : Delegated permissions: full_access_as_user – Access mailbox as signed in user via Exc…
# Cert : https://github.com/Azure-Samples/active-directory-dotnet-daemon-certificate-credential/blob/master/Manual-Configuration-Steps.md
<#
$cert=New-SelfSignedCertificate -Subject "CN=Office365APIDemo" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature
$bin = $cert.RawData
$base64Value = [System.Convert]::ToBase64String($bin)
$bin = $cert.GetCertHash()
$base64Thumbprint = [System.Convert]::ToBase64String($bin)
$keyid = [System.Guid]::NewGuid().ToString()
$jsonObj = @{customKeyIdentifier=$base64Thumbprint;keyId=$keyid;type="AsymmetricX509Cert";usage="Verify";value=$base64Value}
$keyCredentials=ConvertTo-Json @($jsonObj) | Out-File "keyCredentials.txt"
.\"keyCredentials.txt"
#>
$TenantID = "TENANTNAME.onmicrosoft.com"
$AzureADDLLPath = "C:\Temp\AzureAD"
$SourceUser = "Source@TENANTNAME.onmicrosoft.com"
# https://login.windows.net/YOURDIRECTORYNAME.onmicrosoft.com/.well-known/openid-configuration
$TenantID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
# Application ID
$ClientID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
# Provide the path of the certificate file
$certfile = "C:\Scripts\API\Office365APIdemo.pfx"
$certpass = "CertPassword"
# Load ADAL Assemblies
$adal = $AzureADDLLPath + "\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
# Set Resource URI to Office 365 in this case
$resourceAppIdURI = "https://outlook.office365.com/"
# Set Authority to Azure AD Tenant
$authority = "https://login.windows.net/$($TenantID)/oauth2/authorize"
# Create Authentication Context tied to Azure AD Tenant
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
# Acquire token
$flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet
#Provide the password required to access the X.509 certificate data
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certfile, $certpass, $flag )
$cac = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate($clientID, $cert)
$authResult = $authContext.AcquireTokenASync($resourceAppIdURI, $cac)
#Load EWS DLL
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll" -ErrorAction Stop
#Build EWS Service and Credential
$Service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1);
$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.OAuthCredentials($authResult.result.CreateAuthorizationHeader())
$service.httpheaders.Add("X-AnchorMailbox", $SourceUser)
$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$SourceUser)
#Build EWS URL
$URL = "https://outlook.office365.com/ews/exchange.asmx"
$service.Url = [system.URI] $URL
#Send EWS request to get the last 100 emails
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
[array]$Allmails = $inbox.FindItems(100)
$Allmails | select Subject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment