Exchange Online V2 CBA

Quadrotech LAB Administrator 0 Reputation points
2023-02-14T12:58:33.12+00:00

Hi everybody. I am working on a project which fetches the data from Microsoft via Powershell. We are using Exhcnage Online V2 with CBA in place. To connect to ExchangeOnline we are using this script:

var exoV2Cba = @"Param($Bytes, $Password, $AppId, $Organization)
            Import-Module ExchangeOnlineManagement
            $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($Bytes, $Password)
            Connect-ExchangeOnline -Certificate $cert -AppId $AppId -Organization $Organization"

And then we are connecting like this

        using PowerShell powershell = PowerShell.Create();
        powershell.Runspace = runspace;
        PSCommand command = new PSCommand().AddScript(ExolV2Cba);
        foreach (var item in parameters)
        {
            command.AddParameter(item.Key, item.Value);
        }

        powershell.Commands = command;
        var results = await Task.Factory.FromAsync(powershell.BeginInvoke(), powershell.EndInvoke);

        var errors = powershell.Streams.Error.ReadAll();

The parameters array contains the byte array certificate, appId and organizationDomain.

However, the organization domain doesn't contain the "onmicrosoft.com" part as it's required due to documentation. (see https://video2.skills-academy.com/en-us/powershell/exchange/app-only-auth-powershell-v2?view=exchange-ps#connection-examples) So in production it's failing with "For AppOnly flow Tenant in token doesn't match with Tenant in request Url" error. What I don't understand here is why it's working for me when I run the same code locally on my pc. We are using docker so the versions of Powershell and other libriries are the same as in production. Yet locally the script is executing just fine with no errors.

I am also curious why in production it's failing on the stage of executing the data fetching script(Get-ExoMailboxStatistics) and not on the stage of "Connect-ExchangeOnline)

Also notice that we have a $password variable in our script for authorization. However, we don't pass any value there so I m not sure how it works as well. I don't have password for that tenant because it's client's tenant but I have Certificate which I got from debug. So I tried to connect to Exchange Online from my Powershell Console but every time the credentials window pops up asking me for a password.

Thanks for any ideas or suggestions

Microsoft Exchange Online
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.