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

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 Graph is limited to a m

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 need to authorize it in you tenant (eg build a small ap

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th
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.