source/public/Connect-ExOL.ps1

# This functions connects to Exchange Online Remote PowerShell using Token Authentication with ADAL.
# AzureAD Module is required for this function to work.
Function Connect-ExOL {
    [CmdletBinding()]
    param (
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [pscredential]$Credential,
        [parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$TenantID
    )
    # Get the latest ADAL
    try {
        $AzureADBasePath = (Get-Module AzureAD -ListAvailable | Sort-Object Version -Descending)[0].ModuleBase.ToString()
        Add-Type -Path "$AzureADBasePath\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
    }
    catch {
        throw "AzureAD module is required. Please run 'Install-Module AzureAD' to install the module before trying again."
    }

    # if $TenantID is not used, assume the TenantID is the username's domain.
    if (!($TenantID)) {
        $TenantID = ($Credential.UserName -split "@")[1]
    }

    Write-Verbose "Establishing Remote PowerShell Session with Exchange Online."

    Remove-PSSession -Name Exchange -Confirm:$false -ErrorAction SilentlyContinue

    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList "https://login.microsoftonline.com/$tenantID/"
    # EXO AppID
    $client_id = "a0c73c16-a7e3-4564-9a95-2bdf47383716"
    $AADcredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential" -ArgumentList $Credential.UserName, $Credential.Password
    $authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, "https://outlook.office365.com", $client_Id, $AADcredential)

    $Authorization = "Bearer {0}" -f $authResult.Result.AccessToken
    $Password = new-object Security.SecureString
    $Authorization.ToCharArray() | ForEach-Object {$Password.AppendChar($_)}

    $Token = New-Object System.Management.Automation.PSCredential -ArgumentList ($Credential.UserName), $Password
    $Session = New-PSSession -Name Exchange -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true -Credential $Token -Authentication Basic -AllowRedirection

    Import-Module (Import-PSSession $Session -AllowClobber -DisableNameChecking) -Global -WarningAction SilentlyContinue
}