functions/azure/Connect-ToAzureDeviceCode.ps1

function Connect-ToAzureDeviceCode {
    param (
        [Parameter(Mandatory = $true)]
        [guid]$TenantId,
        [guid]$SubscriptionId,
        [uri]$Endpoint = 'https://graph.microsoft.com'
    )

    $clientId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" # Microsoft PowerShell
    $scope = Get-ScopeFromEndpoint -Endpoint $Endpoint

    $deviceCodeResponse = Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/devicecode" `
        -Body @{
            client_id = $clientId
            scope     = "$scope offline_access"
        } -ContentType "application/x-www-form-urlencoded"

    Write-Host "`n📲 Bitte öffnen Sie folgende URL und geben Sie den Code ein:"
    Write-Host "$($deviceCodeResponse.verification_uri)"
    Write-Host "Code: $($deviceCodeResponse.user_code)"
    $deviceCodeResponse.user_code | Set-Clipboard
    Write-Host "`nDer Code wurde in die Zwischenablage kopiert. Sie können ihn jetzt einfügen."
    Start-Process $deviceCodeResponse.verification_uri

    $token = $null
    $maxTries = $deviceCodeResponse.expires_in / $deviceCodeResponse.interval
    for ($i = 0; $i -lt $maxTries; $i++) {
        Start-Sleep -Seconds $deviceCodeResponse.interval
        try {
            $requestTime = Get-Date
            $tokenResponse = Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" `
                -Body @{
                    grant_type  = "urn:ietf:params:oauth:grant-type:device_code"
                    client_id   = $clientId
                    device_code = $deviceCodeResponse.device_code
                } -ContentType "application/x-www-form-urlencoded"

            $token = $tokenResponse.access_token
            break
        } catch {
            if ($_.Exception.Response.StatusCode.Value__ -ne 400) {
                Write-Error $_
                return $false
             }
        }
    }

    if (-not $token) {
        Write-Error "Token konnte nicht bezogen werden (Timeout)!"
        return $false
    }

    $BcAdminSession.AzureTenantId = $TenantId
    $BcAdminSession.AzureSubscriptionId = $SubscriptionId
    $BcAdminSession.AzureClientId = $clientId
    $BcAdminSession.AzureClientSecret = $null

    Update-BcAdminSessionToken -Scope $scope -RequestTime $requestTime -TokenResponse $tokenResponse

    return $true
}