I have one tenant, Let's say abc.com where I have created one enterprise application. Let's say X-app and it is a multi-tenant app. In the other tenant, Let's say xyz.com in that I have granted all the consent to X-app and I can see X-app in the application section of Azure. Now, Using PowerShell I am trying to connect ExchangeOnline of xyz.com using X-app like.
$tenant = 'xyz.onmicrosoft.com' //of xyz.com
$clientId = "xxxxxxxx-87e9-49fc-888e-xxxxxxxxxx" //of X-app
$clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" //of X-app
$tenantId = "xxxxxxxx-e4d4-4859-abf9-xxxxxxxxxxxx" //of xyz.com
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/x-www-form-urlencoded")
$body = "client_id=" + $clientId + "&scope=https%3A%2F%2Foutlook.office365.com%2F.default&grant_type=client_credentials&client_secret=" + $clientSecret
$url = "https://login.microsoftonline.com/" + $tenantId + "/oauth2/v2.0/token"
$response = Invoke-RestMethod $url -Method 'POST' -Headers $headers -Body $body
Connect-ExchangeOnline -Organization $tenant -AccessToken $response.access_token
But it is giving me errors like.
UnAuthorized
At C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.1.0\netFramework\ExchangeOnlineManagement.psm1:733 char:21
+ throw $_.Exception;
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : UnAuthorized
It is working fine when I use abc.com tenant values($tenant and $tenantId) but I need access of xyz.com tenant's ExchangeOnline.
I created Azure AD Multi Tenant application in TenantA and granted API permissions:
I signed in with TenantB user and the application is present in Enterprise application:
In TenantB, make sure to assign any one the roles to the Enterprise application. Refer this MsDoc:
I assigned Exchange Administrator role for the application in both TenantA and TenantB
TenantB:
I am able to connect Exchange online using multi-tenant application successfully:
Reference:
App-only authentication in Exchange Online PowerShell and Security & Compliance PowerShell | Microsoft