Private/Authentication/Microsoft/Get-RefreshedToken.ps1

function Get-RefreshedToken {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [object]$ExistingToken,
        
        [Parameter(Mandatory)]
        [string]$TenantId,
        
        [Parameter(Mandatory)]
        [string]$Scopes
    )
    
    try {
        if ($null -eq $ExistingToken) {
            Write-ModuleLog -Message "Existing token is null" -Level Error -Component 'TokenRefresh' `
                -ThrowError -ErrorOperation 'TokenRefresh' -ErrorMessage 'ExistingToken is null'
        }

        if (!$ExistingToken.refresh_token) {
            Write-ModuleLog -Message "No refresh token available in existing token" -Level Error -Component 'TokenRefresh' `
                -ThrowError -ErrorOperation 'TokenRefresh' -ErrorMessage 'No refresh token available in existing token'
        }

        $body = @{
            client_id = $script:PartnerCredentials.ApplicationId
            client_secret = $script:PartnerCredentials.ApplicationSecret
            grant_type = "refresh_token"
            refresh_token = $ExistingToken.refresh_token
            scope = $Scopes
        }

        try {
            $response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" `
                -Method POST `
                -Body $body `
                -ContentType 'application/x-www-form-urlencoded'
        }
        catch {
            $detailedError = switch -Regex ($_.Exception.Message) {
                'AADSTS70000' { 'Invalid refresh token' }
                'AADSTS700082' { 'The refresh token has expired' }
                default { $_.Exception.Message }
            }
            Write-ModuleLog -Message "Failed to refresh token: $detailedError" -Level Error -Component 'TokenRefresh' -ErrorRecord $_
        }

        $newToken = ConvertFrom-JwtToken -Token $response.access_token
        
        if ($response.refresh_token) {
            $newToken | Add-Member -NotePropertyName 'refresh_token' -NotePropertyValue $response.refresh_token
        }
        
        return $newToken
    }
    catch [TokenOperationException] {
        Write-ModuleLog -Message "An error occurred during token refresh" -Level Error -Component 'TokenRefresh' -ErrorRecord $_
    }
    catch {
        Write-ModuleLog -Message "An unexpected error occurred during token refresh" -Level Error -Component 'TokenRefresh' -ErrorRecord $_
        throw [TokenOperationException]::new(
            'TokenRefresh',
            'An unexpected error occurred during token refresh',
            $_
        )
    }
}