> For the complete documentation index, see [llms.txt](https://docs.devolutions.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.devolutions.net/server/de/knowledge-base/how-to-articles/obtain-rest-api-access-in-a-user-context.md).

# REST-API-Zugriff in einem Benutzerkontext erhalten

In manchen Szenarien müssen Sie möglicherweise den REST-API-Zugriff im Benutzerkontext über den Device Authorization Flow erhalten. Die Schritte zur Einrichtung wurden in PowerShell dokumentiert, aber jede Sprache ist geeignet. So funktioniert es:

1. Fragen Sie den Well-Known-OpenID-Konfigurationsendpunkt ab, um die Token- und Device-Authorization-Endpunkte des Servers abzurufen:

```powershell
try {
    $wellKnownResponse = Invoke-RestMethod -Method Get -Uri $wellKnownEndpoint

    $tokenEndpoint = $wellKnownResponse.token_endpoint
    $deviceCodeEndpoint = $wellKnownResponse.device_authorization_endpoint
} catch {
    Write-Error "Error obtaining server information"
    exit
}
```

2. Senden Sie eine Anfrage an den Device-Authorization-Endpunkt, um einen Device Code, einen User Code, eine Verifizierungs-URL und eine vollständige Verifizierungs-URL zu erhalten, sowie Details dazu, wie lange die Codes gültig sind und wie oft geprüft werden soll. Öffnen Sie dann entweder einen Browser mit der vollständigen Verifizierungs-URL oder weisen Sie den Benutzer an, seinen bzw. ihren User Code manuell einzugeben und die Geräte-Zugriffsanfrage zu genehmigen:

```powershell
$body = "client_id=$clientId&scope=$([uri]::EscapeDataString($scope))"

try {
    $deviceCodeResponse = Invoke-RestMethod -Method Post -Uri $deviceCodeEndpoint `
                            -ContentType "application/x-www-form-urlencoded" -Body $body
} catch {
    Write-Error "Failed to obtain device code: $_"
    exit
}

# Extract values from the response (field names may vary by provider)
$device_code               = $deviceCodeResponse.device_code
$user_code                 = $deviceCodeResponse.user_code
$verification_uri          = $deviceCodeResponse.verification_uri
$verification_uri_complete = $deviceCodeResponse.verification_uri_complete
$interval                  = 10   # in seconds
$expires_in                = $deviceCodeResponse.expires_in   # in seconds

# Provide a default interval if none was returned or if it's zero/null
if (-not $interval -or $interval -eq 0) {
    $interval = 5
    Write-Host "Interval not provided or invalid; defaulting to $interval seconds."
}

# Instead of instructing the user, open the browser to the verification_uri_complete
if ($verification_uri_complete) {
    Write-Host "Opening browser for device authorization..."
    Start-Process $verification_uri_complete
} else {
    Write-Host "verification_uri_complete not provided. Please manually go to $verification_uri and enter the code: $user_code"
}
```

3. Starten Sie eine Schleife, die periodisch eine Anfrage mit dem Device Code und der Client-ID an den Token-Endpunkt sendet, bis der Server ein Access Token zurückgibt:

```powershell
$startTime = Get-Date
$tokenResponse = $null

while (((Get-Date) - $startTime).TotalSeconds -lt $expires_in) {
    Start-Sleep -Seconds $interval

    try {# Build the POST body to exchange the device code for an access token
        $tokenBody = "grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=$clientId&device_code=$device_code"
        $tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $tokenBody

        if ($tokenResponse.access_token) {
            Write-Host "Access token obtained:" $tokenResponse.access_token
            break
        }
    }
    catch {# Instead of reading the response content (which may be disposed), use the exception message.
        $errorMessage = $_.Exception.Message

        # Check if the exception message indicates that authorization is still pending.
        if ($errorMessage -match "authorization_pending") {
            Write-Host "Authorization pending..."
            continue
        }
        else {
            Write-Error "Error during token polling: $errorMessage"
            break
        }
    }
}

if (-not $tokenResponse -or -not $tokenResponse.access_token) {
    Write-Host "Failed to obtain an access token or authorization expired."
}
```

4. Verwenden Sie bei Bedarf das in Schritt 1 erhaltene Refresh Token, um ein neues Token vom Token-Endpunkt anzufordern und so den kontinuierlichen Zugriff auf die Anwendung sicherzustellen:

```powershell
$body = "grant_type=refresh_token&authorization=bearer $($tokenResponse.access_token)&refresh_token=$($tokenResponse.refresh_token)&client_id=dvls"

try {
    $refreshResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $body

    if ($refreshResponse.access_token) {
        Write-Host "Access token obtained:" $tokenResponse.access_token
        break
    }
} catch {
    Write-Error "Failed to obtain device code: $_"
    exit
}
```

{% hint style="info" %}
Weitere Informationen zum Device Authorization Flow finden Sie in [Oktas Dokumentation](https://auth0.com/docs/get-started/authentication-and-authorization-flow/device-authorization-flow).
{% endhint %}

### Siehe auch

* [REST-API-Dokumentation](/server/de/web-interface/utilities/api-documentation.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.devolutions.net/server/de/knowledge-base/how-to-articles/obtain-rest-api-access-in-a-user-context.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
