functions/azure/Connect-ToAzure.ps1

function Connect-ToAzure {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [guid]$TenantId,

        [Parameter(Mandatory = $false)]
        [guid]$SubscriptionId = [guid]::Empty,

        [Parameter(Mandatory = $false)]
        [guid]$ClientId,

        [Parameter(Mandatory = $false)]
        [object]$ClientSecret,

        [Parameter(Mandatory = $true)]
        [string]$Endpoint,

        [Parameter(Mandatory = $false)]
        [string]$ApiVersion = $BcAdminSession.AzureRestApiVersion,

        [Parameter(Mandatory = $false)]
        [switch]$Force
    )

    $scope = Get-ScopeFromEndpoint -Endpoint $Endpoint

    # TODO support refresh_token flow
    if ($null -ne $BcAdminSession.AzureAccessTokens -and
        $null -ne $BcAdminSession.AzureAccessTokens[$scope] -and
        $null -ne $BcAdminSession.AzureAccessTokens[$scope].valid_to) {
        if (($BcAdminSession.AzureAccessTokens[$scope].valid_to -gt (Get-Date).AddSeconds(60)) -and -not $Force) {
            return $true
        } else {
            if ([guid]::Empty -eq $ClientId) {
                $ClientId = $BcAdminSession.AzureClientId
            }
            if ($ClientSecret -is [SecureString]) {
                if (([string]::IsNullOrWhiteSpace($ClientSecret))) {
                    $ClientSecret = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($BcAdminSession.AzureClientSecret))
                }
            } elseif(-not ($ClientSecret -is [string])) {
                Write-Error "ClientSecret has to be of type [SecureString] or [String]!"
                return $false
            }
            if ([guid]::Empty -eq $TenantId) {
                $TenantId = $BcAdminSession.AzureTenantId
            }
            if ([guid]::Empty -eq $SubscriptionId) {
                $SubscriptionId = $BcAdminSession.AzureSubscriptionId
            }
        }
    } else {
        Test-AzContextAndConnect -TenantId $TenantId -ServicePrincipalName $ClientId -Endpoint $Endpoint
    }

    if ($ClientSecret -is [SecureString]) {
        [string]$ClientSecret = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($ClientSecret))
    }

    if (([guid]::Empty -eq $ClientId) -or ([string]::IsNullOrWhiteSpace($ClientSecret))) {
        Write-Error "Unable to connect to Microsoft Azure!"
    }
    
    $body = @{
        grant_type    = "client_credentials"
        client_id     = $ClientId
        client_secret = $ClientSecret
        scope         = $scope
    }

    $requestTime = Get-Date
    $tokenResponse = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Body $body -ContentType "application/x-www-form-urlencoded"

    if ($tokenResponse)
    {
        if (-not ([string]::IsNullOrWhiteSpace($ApiVersion))) {
            $BcAdminSession.AzureRestApiVersion = $ApiVersion
        }

        $BcAdminSession.AzureTenantId = $TenantId
        $BcAdminSession.AzureSubscriptionId = $SubscriptionId
        $BcAdminSession.AzureClientId = $ClientId
        $BcAdminSession.AzureClientSecret = ConvertTo-SecureString $ClientSecret -AsPlainText -Force

        Update-BcAdminSessionToken -Scope $scope -RequestTime $requestTime -TokenResponse $tokenResponse
        
        return $true
    } else {
        Write-Warning "Microsoft Azure Authentifizierung fehlgeschlagen!"
        return $false
    }
}