Private/Invoke-DuneApiAuthCredential.ps1

function Invoke-DuneApiAuthCredential () {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateSet("Prod", "Dev","Test","Local")]
        [string]$DuneInstance,

        [Parameter(Mandatory)]
        [string]$Tenant,

        [Parameter(Mandatory)]
        [PSCredential]$Credential
    )

    $DuneApiUrl = Get-DuneApiUrl -DuneInstance $DuneInstance

    # Save websession/jwt/pass
    $AuthUrl = "{0}{1}" -f $DuneApiUrl, "/auth/credentials"
    $Headers = @{
        "Accept"       = "application/json"
        "Content-Type" = "application/json"
        "X-Tenant"     = $Tenant
    }
    Write-Debug "$($MyInvocation.MyCommand)|process|Getting new session ..."
    $UserName = $Credential.UserName
    $Response = Invoke-WebRequest -Uri $AuthUrl -Method POST -Headers $Headers -Body (@{UserName = $UserName; Password = (Get-PlainPasswordFromCredential -Credential $credential) } | ConvertTo-Json) -UseBasicParsing -SessionVariable AuthSession #UseBasicParsing needed for Az Automation (otherwise internet explorer first launch errorappears) / SkipCertificateCheck not available on Azure
    if ($Response.StatusCode -ne 200) {
        throw "Something went wrong with the web request ..."
    }
    if ($null -eq $AuthSession) {
        Write-Warning "AuthSession not returned"
    }
    else{
        Write-Verbose "Successfully established dune AuthSession"
    }

    # save auth info
    if ($AuthSession -and (-not $DuneSession.AuthSession)) {
        $Script:DuneSession = [PSCustomObject]@{
            Type         = 'Credential'
            DuneApiUrl   = $DuneApiUrl
            AuthSession  = $AuthSession
            SessionUser  = $UserName
            Tenant       = $Tenant
        }
    }
    else {
        Write-Warning "Skipped writing new DuneSession, as Session already exists" # workaround as AuthSession is not available on second invocation (on sequential workflow)
    }
}