Private/Confirm-JiraConnection.ps1

function Confirm-JiraConnection {
    <#
    .SYNOPSIS
        Prüft, ob eine aktive Jira-Verbindung besteht, und gibt den Auth-Header zurück.
    #>

    [CmdletBinding()]
    param ()

    process {
        if (-not $script:JIRA_AuthHeader) {
            Throw "Keine aktive Jira-Verbindung. Zuerst Connect-Jira ausführen."
        }

        if ($script:JIRA_TokenExpiresAt -and (Get-Date).AddSeconds(30) -ge $script:JIRA_TokenExpiresAt) {
            Write-Verbose "OAuth2 Access Token abgelaufen (oder läuft gleich ab) - hole neues Token via client_credentials"

            $PlainClientSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
                [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($script:JIRA_ClientSecret)
            )
            $TokenBody = @{
                client_id     = $script:JIRA_ClientId
                client_secret = $PlainClientSecret
                grant_type    = 'client_credentials'
            }
            $ProxyParams = Get-JiraProxyParams

            try {
                $TokenResponse = Invoke-RestMethod -Method Post -Uri 'https://auth.atlassian.com/oauth/token' -Body $TokenBody @ProxyParams
            }
            catch {
                Write-Error $_.Exception.Message
                Throw "Erneuerung des Access Tokens fehlgeschlagen."
            }

            $script:JIRA_AuthHeader = @{ Authorization = "Bearer $($TokenResponse.access_token)" }
            $script:JIRA_TokenExpiresAt = (Get-Date).AddSeconds($TokenResponse.expires_in)
        }
    }

    end {
        return $script:JIRA_AuthHeader
    }
}