Skip to main content

Dependency free Generic EWS oAuth PowerShell example for Office365

Microsoft recently posted an update that will affect those people who use EWS in applications and script against Office365 https://blogs.technet.microsoft.com/exchange/2018/07/03/upcoming-changes-to-exchange-web-services-ews-api-for-office-365 

While 2020 is a few years away what this means is that if you are using Basic Authentication in your EWS scripts or applications that on the 13th October 2020 your app will stop working. Given the amount of time you have and the changes required to support oAuth nobody should really be caught out by this but procrastination and people not understanding legacy applications will mean I'm sure this date won't pass without any infamy.

Within PowerShell scripts you have two options to generate the oAuth tokens you need to keep you script working. One is to use a dependency library like ADAL to do it which Ingo posted a really good write up for https://ingogegenwarth.wordpress.com/2018/08/02/ews-and-oauth the other is just create some of your own script code to do the Authentication and managed of the Tokens. As part of my Exch-Rest library because I wanted to make this dependency free I wrote my own routines for Getting and Renewing OAuth tokens needed which can also be used for EWS . So in this post I've separated those out and included them into a simple header script that can be used to do oAuth against Office365.

EWS Managed API and oAuth

If you using the EWS Managed API in your scripts which the majority of people do it contains code already to add the correct Bearer headers in for Oauth if you use  the OAuthCredentials class


        $OAuthCredentials = New-Object Microsoft.Exchange.WebServices.Data.OAuthCredentials((ConvertFrom-SecureStringCustom -SecureToken $Script:Token.access_token))
        $service.Credentials = $OAuthCredentials

If your using the ADAL library be aware while its correct to say it does have a TokenCache and code to refresh the tokens once they expire this won't work with the EWS Managed API. As you can see from the code above because you only pass in the Access_Token (as a String) into this class it doesn't do any active management of the Token from that point. This means if you just pass in the AccessToken from whatever method you used to generated it if your script runs for more then one hour your code will fail at the 60 minute point. Unfortunately the EWS Managed API doesn't have a CallBack to use where you could link in the ADAL libraries refresh function (or your own code to manage the token refresh) to check before making a request. So one important modification you should make to your code if before it makes an EWS call (eg Bind,Load,findItems etc) you will need to add in code to check for expired tokens. The ADAL has the acquiretokensilentasync method for this (this will return the token from cache or renew if necessary), in the code in my example I have the Invoke-ValidateToken function which does the renewal after 50 minutes to avoid token expiration.

Application registrations

Its always a good idea to create your own application registration as this gives you the ultimate control over what rights a script or application will have in your environment (although EWS really only has one grant that will work which is full Mailbox Access). But creating you own ApplicationId's allows you  track the use of the ApplicationId and potential audit the miss use of a particular application more effectively. For scripts using the Native application type and the Out of Band redirect(urn:ietf:wg:oauth:2.0:oob) is generally a good idea as you won't have an registered endpoint online to redirect the Authentication to once its complete. There are some good walk throughs to do this https://blogs.technet.microsoft.com/dawiese/2017/04/15/get-office365-usage-reports-from-the-microsoft-graph-using-windows-powershell/ shows the newer portal screens.

Last word on security

While oAuth is a great improvement in security over basic Authentication its not the panacea in itself for the InfoSec issues the IT industry faces as a whole. So you should see implementing oAuth as a step in the right direction but be careful and always treat access tokens like you would usernames and passwords (eg don't store them in plain text) and look at always strengthening your authentication with measures like Multi-Factor Authentication. 


The script includes a Test function which just binds to the Inbox so you use it like

Import-Module .\GenericOauthEWS.ps1 -Force

Test-EWSConnection -MailboxName gscales@datarumble.com

Testing

Like any script you get off the Internet you should always do your own testing but consider these points of failure for Oauth tokens that you wouldn't have to have previously considered with Basic Auth

  • If things run for more the 1 hour does my token renew correctly
  • If the AccessToken suddenly becomes Invalid for X Reason and I get a 401 error in my code will it handle the reauth (using the RefreshToken). (for the second part you need to build in an exception handler in you code for 401 error when using oAuth)
Regional Azure Endpoints

This script is hardcoded to use the common (Production) Azure Authentication endpoint that the majority of Office365 Tenants would use however some regions like China,Germany and US Government have their own dedicated endpoint so you would need to change the URL in this case see https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/extending-sharepoint-online-for-germany-china-usgovernment-environments . There are ways of discovering the Endpoint dynamically which I'll included in future updates of the script.

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

How to access and restore deleted Items (Recoverable Items) in the Exchange Online Mailbox dumpster with the Microsoft Graph API and PowerShell

As the information on how to do this would cover multiple posts, I've bound this into a series of mini post docs in my GitHub Repo to try and make this subject a little easier to understand and hopefully navigate for most people.   The Binder index is  https://gscales.github.io/Graph-Powershell-101-Binder/   The topics covered are How you can access the Recoverable Items Folders (and get the size of these folders)  How you can access and search for items in the Deletions and Purges Folders and also how you can Export an item to an Eml from that folder How you can Restore a Deleted Item back to the folder it was deleted from (using the Last Active Parent FolderId) and the sample script is located  https://github.com/gscales/Powershell-Scripts/blob/master/Graph101/Dumpster.ps1

Using the MSAL (Microsoft Authentication Library) in EWS with Office365

Last July Microsoft announced here they would be disabling basic authentication in EWS on October 13 2020 which is now a little over a year away. Given the amount of time that has passed since the announcement any line of business applications or third party applications that you use that had been using Basic authentication should have been modified or upgraded to support using oAuth. If this isn't the case the time to take action is now. When you need to migrate a .NET app or script you have using EWS and basic Authentication you have two Authentication libraries you can choose from ADAL - Azure AD Authentication Library (uses the v1 Azure AD Endpoint) MSAL - Microsoft Authentication Library (uses the v2 Microsoft Identity Platform Endpoint) the most common library you will come across in use is the ADAL libraries because its been around the longest, has good support across a number of languages and allows complex authentications scenarios with support for SAML etc. The
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.