In this article
July 25, 2025
July 25, 2025

How to add auth to your Python CLI using WorkOS

Authenticate users in your Python command-line tool with a secure OAuth 2.0 Device Code flow using WorkOS. This tutorial shows how to implement login via the terminal, step by step.

Modern CLI apps often need to authenticate users, and using a simple web-based OAuth flow is the cleanest way to do it.

In this tutorial, we’ll implement a CLI login flow using WorkOS CLI Auth to authenticate users from the command line by using a web browser. Based on the OAuth 2.0 Device Authorization Grant, this method is perfect for CLIs where embedding a browser isn't feasible.

In this guide, we’ll walk through how to add auth to your Python CLI using WorkOS, step by step.

What we will build

You’ll create a Python CLI that:

  1. Requests a device code from WorkOS: The CLI starts the login flow by contacting WorkOS to get a device_code (for itself) and a user_code (for the user), along with a URL the user should visit.
  2. Displays a user-friendly prompt: The CLI prints the user_code and verification URL in the terminal, and optionally opens the browser automatically for the user to log in and approve.
  3. Polls WorkOS while the user logs in: As the user completes authentication in the browser, the CLI quietly checks in with WorkOS every few seconds to see if the user has completed the login.
  4. Exchanges the device code for tokens: Once authorized, the CLI receives an access token ready to make authenticated API calls.

This flow is ideal for tools running in environments that can’t easily embed a browser window (like the terminal), and it avoids the need to paste auth tokens manually. Let’s dive in.

Prerequisites

Before starting, make sure you have:

Step 1: Start the auth flow from the CLI

Start by initiating the device authorization flow from your CLI tool. This will generate a user-facing code and a verification URL.

  
import requests

def request_device_code(client_id: str):
    resp = requests.post(
        "https://api.workos.com/user_management/authorize/device",
        data={"client_id": client_id},
    )
    resp.raise_for_status()
    return resp.json()
  

This function hits the WorkOS Device Authorization endpoint and retrieves:

  • device_code: For your CLI only.
  • user_code: To show the user.
  • verification_uri_complete: A URL users can click to authorize.
  • interval: How often to poll for the token.
  
{
  "device_code": "71azDp28ToiCscGDvLxnXLkuuFRMrnd4V7rdsjIlBPXuy13j8GOzU0aZHb46tsz3",
  "user_code": "RRGQ-BJVS",
  "verification_uri": "https://smart-chefs.authkit.app/device",
  "verification_uri_complete": "https://smart-chefs.authkit.app/device?user_code=ABCD-EFGH",
  "expires_in": 300,
  "interval": 5
}
  

Step 2: Prompt the user to authenticate

Display the user code and link in the terminal. Optionally, open the browser automatically.

  
import webbrowser

def prompt_user(data: dict):
    print("\nTo sign in")
    print(f"Visit: {data['verification_uri']}")
    print(f"Enter code: {data['user_code']}")
    print(f"Or open: {data['verification_uri_complete']}")
    try:
        webbrowser.open(data["verification_uri_complete"])
    except webbrowser.Error:
        pass

  

Note the following:

  • Always display the user_code and verification_uri to the user.
  • Never show the device_code, it’s only used internally for polling.

Step 3: Poll for access tokens

While the user authenticates in their browser, your app should poll the token endpoint.

  
import time

def poll_for_tokens(client_id: str, device_code: str, expires_in: int, interval: int):
    deadline = time.time() + expires_in
    while time.time() < deadline:
        resp = requests.post(
            "https://api.workos.com/user_management/authenticate",
            data={
                "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
                "device_code": device_code,
                "client_id": client_id,
            },
        )
        if resp.status_code == 200:
            return resp.json()
        data = resp.json()
        err = data.get("error")
        if err == "authorization_pending":
            time.sleep(interval)
        elif err == "slow_down":
            interval += 1
            time.sleep(interval)
        else:
            raise RuntimeError("Authorization failed: " + err)
    raise TimeoutError("Authorization timed out")
  

Note the following:

  • Poll at the interval specified in the authorization response (every 5 seconds).
  • Respect slow_down errors by increasing your polling interval.
  • Stop polling when you receive access_denied or expired_token errors.
  • Implement a reasonable timeout to avoid infinite polling.

The response looks like this:

  
{
  "user": {
    "object": "user",
    "id": "user_01JYHX0DW7077GPTAY8MZVNMQX",
    "email": "grant.mccode@workos.com",
    "email_verified": true,
    "first_name": "Grant",
    "last_name": "McCode",
    "profile_picture_url": null,
    "last_sign_in_at": "2025-06-25T19:16:35.647Z",
    "created_at": "2025-06-25T01:20:21.355Z",
    "updated_at": "2025-06-25T19:16:35.647Z",
    "external_id": null
  },
  "organization_id": "org_01JYHNPKWTD5DRGPJHNYBB1HB8",
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkdyYW50IE1jQ29kZSIsImFkbWluIjp0cnVlLCJpYXQiOjEzMzcsInBhc3N3b3JkIjoiaHVudGVyMiJ9.kcmTbx7M89k-3qUXN1UVcy9us6xdPZkDOqQ0UeY3Bws",
  "refresh_token": "RSzR4ngmJROKFJZQEpp5fNF4y",
  "authentication_method": "GoogleOAuth"
}
  

Putting it all together

  
def main():
    client_id = "YOUR_CLIENT_ID"
    data = request_device_code(client_id)
    prompt_user(data)
    response = poll_for_tokens(
        client_id, data["device_code"], data["expires_in"], data["interval"]
    )
    print("\nAuthentication successful!")
    print("Access Token:", response["access_token"])
  

That’s it! You’ve just added OAuth-powered login to your CLI.

Your users can now authenticate securely through the browser, without ever pasting tokens by hand.

This site uses cookies to improve your experience. Please accept the use of cookies on this site. You can review our cookie policy here and our privacy policy here. If you choose to refuse, functionality of this site will be limited.