Exchange Online PowerShell with MFA enforced using Azure Automation
>> The Problem
Securely accessing Exchange Online PowerShell with privileged access (Exchange Administrator) while MFA is enforced through Conditional Access has been a real headache for many admins.
For scheduled tasks or Azure Automation, connecting to Exchange Online PowerShell is a must for any scripted solution. But with Conditional Access and MFA enforcement, many scripts have broken.
A quick fix is to exclude the account or set up conditions in Conditional Access to allow a non-MFA connection. But connecting without exclusions and keeping enforcement in place is what we really want.
UPDATE: Here is a requested example using Managed Identities, which is a much better approach:
>> Service Principals with Certificates to the rescue
Service Principals or App registrations in Azure AD are secure modern authentication entities that can give applications access to Microsoft Online Services.
The official ExchangeOnlineManagement V2 module now supports the use of Certificate-Based Authentication with Service Principals.
>> How to - Azure Automation
If you created your Azure Automation account with a "RunAs" account, it would already have a Service Principal with a certificate (that expires every year).
With a RunAs account in Azure Automation, first install the ExchangeOnlineManagement PowerShell Module into your Azure Automation Account.
After running, go to the App registration in Azure AD and GRANT ADMIN CONSENT.
>> How to - Scheduled Tasks
If running scripts from On-Prem, consider Azure Automation instead (it has a free option). If you must use task scheduler, create the App Registration manually and assign permissions as above.
>> Create a self-signed certificate for app registration authentication
>> [powershell]
<#
Script to create self-signed 10 year valid cert and upload to App Registration
Microsoft has come a long way with the new PowerShell modules. However, granularity on the backend is still missing, and the true Graph experience for Exchange Automation is not fully there yet.