Private/PartnerActions/Get-SAMTokens.ps1

function Get-SAMTokens() {
    # Get current Azure context
    $AzContext = Get-AzContext
    # Check if we are already logged in to the partner tenant, if not, log in.
    if (!$AzContext -or $AzContext.Tenant.Id -ne $PartnerTenantId) {
        try {
            $Certificate = Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.Thumbprint -eq "3f6bac856f77174b1f0bdb846382b547767f9a4c" }
            if($Certificate) {
                Write-Host "Found certificate with thumbprint 'C6410527E3659D36BE49D5A7F99D08EF9C6CE95A' on the machine." -ForegroundColor DarkGray
                Connect-AzAccount -ApplicationId "9a566784-17d0-43a5-a94e-d0e419dda3a5" -CertificateThumbprint $Certificate.Thumbprint -Tenant $PartnerTenantId -SubscriptionName $SubscriptionName -ErrorAction Stop | Out-Null
            } else {
                Write-Host "Please log in to Azure with your @jlhosting.dk account. A browser window has been opened." -ForegroundColor Yellow
                Connect-AzAccount -Tenant $PartnerTenantId -SubscriptionName $SubscriptionName -ErrorAction Stop | Out-Null
            }
        }
        catch {
            throw "Failed to connect to Azure. Please make sure you have the Az module installed: $_"
        }
    }

    try {
        # Retreive all required values from Azure Key Vault
        $ApplicationId = Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name "ApplicationId" -AsPlainText -ErrorAction Stop
        $ApplicationSecret = Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name "ApplicationSecret" -AsPlainText -ErrorAction Stop
        $RefreshToken = Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name "RefreshToken" -AsPlainText -ErrorAction Stop
        $ExchangeRefreshToken = Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name "ExchangeRefreshToken" -AsPlainText -ErrorAction Stop
        $ApplicationCredential = (New-Object System.Management.Automation.PSCredential ($ApplicationId, (ConvertTo-SecureString $ApplicationSecret -AsPlainText -Force)))
        $ApplicationCertificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList ([Convert]::FromBase64String((Get-AzKeyVaultSecret -VaultName $KeyVaultName -Name "AppRegistration" -AsPlainText -ErrorAction Stop))), '', 'Exportable,MachineKeySet,PersistKeySet'
    }
    catch {
        throw "Failed to connect to Azure Key Vault and retreive secrets: $_"
    }
    # Return all values as a custom object
    return [PSCustomObject]@{
        ApplicationId         = $ApplicationId
        ApplicationSecret     = $ApplicationSecret
        RefreshToken          = $RefreshToken
        ExchangeRefreshToken  = $ExchangeRefreshToken
        ApplicationCredential = $ApplicationCredential
        ApplicationCertificate = $ApplicationCertificate  
    }
}