A minimal example of OAuth2 authentication for CLI applications in headless environments (e.g., over SSH).
sequenceDiagram
participant CLI
participant User
participant OAuth Server
CLI->>OAuth Server: 1. Request device code
OAuth Server->>CLI: 2. Return device_code + user_code
CLI->>User: 3. Display URL and code
User->>OAuth Server: 4. Open URL, enter code, authorize
CLI->>OAuth Server: 5. Poll for token
OAuth Server->>CLI: 6. Return access_token
CLI->>OAuth Server: 7. Make authenticated API requests
- Docker
- Python 3.8+
# Start the mock OAuth2 server
docker compose up -d
# Run the CLI
cd cli
pip install -r requirements.txt
python cli.pyOpen the displayed URL on any device with a browser, enter the code, and authorize.
CLI OAuth2 Demo (Device Flow)
========================================
1. Requesting device code...
2. Open this URL in any browser:
http://localhost:8080/default/device
Enter code: ABCD-1234
(Expires in 600 seconds)
3. Waiting for authorization.....
Received access token: eyJraWQiOiJkZWZhdWx0...
4. Fetching user info with access token...
========================================
Authentication successful!
========================================
User Info:
sub: demouser
azp: cli-app
iss: http://localhost:8080/default
The CLI (cli/cli.py) implements OAuth2 Device Authorization Grant (RFC 8628):
- Request device code: POST to
/device/authorizewith client_id and scope - Display instructions: show verification URL and user code to enter
- Poll for token: repeatedly POST to
/tokenuntil user completes authorization - Handle polling responses:
authorization_pending(keep waiting),slow_down(increase interval),access_denied(user denied),expired_token(timed out) - Make authenticated requests: use access token to call protected APIs
- No redirect URI: no local server needed, can't be intercepted
- Short user codes: easy to type, time-limited
- Polling-based: device never exposes any ports
- User verification: user must actively enter code on trusted device
cd cli && pytest tests/ -vProviders supporting Device Authorization Grant:
| Provider | Documentation |
|---|---|
| Limited Input Device | |
| Microsoft | Device Code Flow |
| GitHub | Device Flow |
To use with a real provider:
- Register your application with the provider
- Update
OAUTH_SERVERandCLIENT_IDincli.py - Add any required scopes