0
# Device Flow
1
2
OAuth 2.0 device authorization grant (RFC 8628) for input-constrained devices like smart TVs, game consoles, and IoT devices. Provides device and user codes for out-of-band authorization.
3
4
## Capabilities
5
6
### Device Client
7
8
OAuth 2.0 client implementation for device authorization flow.
9
10
```python { .api }
11
class DeviceClient:
12
def prepare_device_authorization_request(
13
self,
14
device_authorization_endpoint: str,
15
scope: str | list[str] | None = None,
16
**kwargs,
17
) -> tuple[str, dict[str, str], str]:
18
"""Prepare device authorization request."""
19
20
def prepare_token_request(
21
self,
22
token_url: str,
23
device_code: str,
24
**kwargs,
25
) -> tuple[str, dict[str, str], str]:
26
"""Prepare device token request."""
27
```
28
29
### Device Authorization Endpoint
30
31
Server endpoint for handling device authorization requests.
32
33
```python { .api }
34
class DeviceAuthorizationEndpoint:
35
def create_device_authorization_response(
36
self,
37
uri: str,
38
http_method: str = "POST",
39
body: str | None = None,
40
headers: dict[str, str] | None = None,
41
**kwargs,
42
) -> tuple[dict[str, str], str, int]:
43
"""Create device authorization response with device and user codes."""
44
```
45
46
### Device Application Server
47
48
Pre-configured server for device flow combining device authorization and token endpoints.
49
50
```python { .api }
51
class DeviceApplicationServer:
52
def __init__(self, request_validator, **kwargs): ...
53
```
54
55
## Usage Example
56
57
```python
58
from oauthlib.oauth2.rfc8628 import DeviceClient
59
import requests
60
import time
61
62
# Device flow example
63
client = DeviceClient('your-client-id')
64
65
# Step 1: Get device and user codes
66
device_auth_url, headers, body = client.prepare_device_authorization_request(
67
'https://auth.example.com/device/authorize',
68
scope=['read', 'write']
69
)
70
71
response = requests.post(device_auth_url, headers=headers, data=body)
72
device_data = response.json()
73
74
print(f"Visit: {device_data['verification_uri']}")
75
print(f"Enter code: {device_data['user_code']}")
76
print("Or visit complete URI:", device_data.get('verification_uri_complete'))
77
78
# Step 2: Poll for token
79
device_code = device_data['device_code']
80
interval = device_data.get('interval', 5)
81
82
while True:
83
token_url, headers, body = client.prepare_token_request(
84
'https://auth.example.com/token',
85
device_code=device_code
86
)
87
88
response = requests.post(token_url, headers=headers, data=body)
89
90
if response.status_code == 200:
91
token = response.json()
92
print("Access token received:", token['access_token'])
93
break
94
elif response.status_code == 400:
95
error = response.json()
96
if error['error'] == 'authorization_pending':
97
time.sleep(interval)
98
continue
99
elif error['error'] == 'slow_down':
100
interval += 5
101
time.sleep(interval)
102
continue
103
else:
104
print("Authorization failed:", error)
105
break
106
```