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

Exporting and Uploading Mailbox Items using Exchange Web Services using the new ExportItems and UploadItems operations in Exchange 2010 SP1

Two new EWS Operations ExportItems and UploadItems where introduced in Exchange 2010 SP1 that allowed you to do a number of useful things that where previously not possible using Exchange Web Services. Any object that Exchange stores is basically a collection of properties for example a message object is a collection of Message properties, Recipient properties and Attachment properties with a few meta properties that describe the underlying storage thrown in. Normally when using EWS you can access these properties in a number of a ways eg one example is using the strongly type objects such as emailmessage that presents the underlying properties in an intuitive way that's easy to use. Another way is using Extended Properties to access the underlying properties directly. However previously in EWS there was no method to access every property of a message hence there is no way to export or import an item and maintain full fidelity of every property on that item (you could export the...

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You ...

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Gr...
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.