Problem Description
I am trying to use Connect-ExchangeOnline
with a managed identity in an Azure Automation account to run unattended scripts. While the command works perfectly on my local machine, it fails in the Automation account with an Unauthorized
error.
My Setup
ExchangeOnlineManagement
module installed (tried versions 3.7.1, 3.5, and 3.2)Connect-ExchangeOnline -ManagedIdentity -Organization "us.onmicrosoft.com" -ManagedIdentityAccountID "XYZ123"
Error message:
UnAuthorized
At C:\usr\src\PSModules\ExchangeOnlineManagement\netFramework\ExchangeOnlineManagement.psm1:755 char:21
+ throw $_.Exception;
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : UnAuthorized
What I have tried
Verified identity permissions:
Tested different identities:
System identity not found
Checked Microsoft documentation and forums:
Any guidance or a working example would be greatly appreciated!
By adding the Exchange.ManageAsApp permission to the managed identity, you should be able to resolve the Unauthorized error that you're seeing. Without this step, the managed identity won’t have the necessary permissions to manage Exchange Online resources, even though it might have the Exchange-related roles.
Search for your user-assigned managed identity in the Enterprise Applications section or directly search for the Azure Automation account if you're using the system-assigned identity.
Navigate to API permissions click Add a permission Select APIs my organization uses and search for Office 365 Exchange online.
Select it and then choose Application permissions. Search Exchange.ManageAsApp Click it.
After adding the permission, grant Admin consent for the permissions to take effect.
For managing M365 groups, switch to the Microsoft Graph API since the *-UnifiedGroup
cmdlets have issues with managed identities.
use the Microsoft.Graph
module to authenticate and interact with it using a managed identity:
Connect-MgGraph -ManagedIdentity
#to get all M365 Groups
Get-MgGroup