Skip to content

Authenticating with the API (PKCE) ​

This guide explains how external applications (CLI tools, desktop apps, third-party integrations) authenticate with Fleet using the OAuth 2.0 Authorization Code Grant with PKCE (Proof Key for Code Exchange).

Overview ​

Fleet uses a standard PKCE flow extended with workspace and environment selection. After authenticating, the user chooses which workspace and environment to operate in. The issued JWT token encodes this context, so the external application knows the user's active scope.

Flow diagram ​

External appBrowserFleet server1. generate code_verifier, code_challenge, state2. open authorization URLGET /auth/authorize?code_challenge=…3. login page (if needed)4. user authenticates5. workspace + environment selection6. user selects workspace and environment7. redirect_uri?code=…&state=…8. exchange code + code_verifierPOST /api/v1/oauth2/token9. JWT access token + workspace/environment context10. GET /api/v1/auth/status — optional, full session context

Step-by-step implementation ​

Step 1: Generate PKCE parameters ​

Generate a random code_verifier (43-128 characters, URL-safe) and derive the code_challenge:

code_challenge = BASE64URL(SHA256(code_verifier))

Also generate a random state parameter for CSRF protection.

Step 2: Open the authorization URL ​

Open the user's browser to:

GET {fleet_url}/auth/authorize
  ?client_id={your_app_id}
  &redirect_uri={your_callback_url}
  &code_challenge={code_challenge}
  &code_challenge_method=S256
  &state={state}
ParameterRequiredDescription
client_idYesYour application identifier.
redirect_uriYesURL to receive the authorization code.
code_challengeYesS256 hash of your code_verifier.
code_challenge_methodYesMust be S256.
stateNoRandom string for CSRF protection.

The redirect_uri must point to a local URL your application controls (e.g. http://127.0.0.1:{port}/callback).

Steps 3-6: User authenticates and selects context ​

Fleet handles the interactive part:

  1. If the user is not logged in, they see a login page.
  2. After authentication, a workspace and environment selection page is shown.
  3. The user picks:
    • A workspace — whose resources they want to access.
    • An environment — optionally scoping to a specific environment (e.g. "production", "development"), or "All Environments".

This selection is encoded into the authorization code.

Step 7: Receive the authorization code ​

Fleet redirects the browser to your redirect_uri:

{redirect_uri}?code={authorization_code}&state={state}

Verify that state matches what you sent in Step 2.

Step 8: Exchange the code for a token ​

POST {fleet_url}/api/v1/oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&client_id={your_app_id}
&redirect_uri={your_callback_url}
&code={authorization_code}
&code_verifier={code_verifier}
ParameterRequiredDescription
grant_typeYesMust be authorization_code.
client_idYesSame as in Step 2.
redirect_uriYesSame as in Step 2 (must match exactly).
codeYesThe authorization code from the callback.
code_verifierYesThe original code_verifier (plain text, not the hash).

Step 9: Token response ​

json
{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "token_type": "Bearer",
  "workspace": "64a1b2c3d4e5f6789...",
  "workspace_user": "highercomve",
  "environment": "64f7a8b9c0d1e2345..."
}
FieldDescription
access_tokenJWT Bearer token for API calls.
token_typeAlways Bearer.
workspaceID of the selected workspace (owner account ID).
workspace_userNick/username of the workspace owner.
environmentID of the selected environment (empty if "All Environments").

JWT token claims ​

The access_token is an RS256-signed JWT. Its claims tell you the active context:

ClaimDescription
idThe authenticated user's account ID.
nickThe authenticated user's username.
prnThe user's Pantacor Resource Name.
workspaceThe workspace being accessed (empty = user's own workspace).
workspace_userThe workspace owner's nick (empty = user's own workspace).
environmentActive environment ID (empty = all environments).
environment_idsAllowed environment IDs (when scoped by permission).
expExpiration time.

Determining access context ​

if workspace == "" or workspace == id:
    -> User is operating on their OWN workspace (full access as owner)
else:
    -> User is a GUEST on someone else's workspace
    -> workspace_user tells you whose workspace it is

if environment == "":
    -> User sees ALL environments (no filter)
else:
    -> User is scoped to a SPECIFIC environment

Status endpoint ​

For a richer view of the session context, use the status endpoint:

GET {fleet_url}/api/v1/auth/status
Authorization: Bearer {access_token}
json
{
  "user": { "id": "64a1b2c3...", "nick": "sergiomarin002", "prn": "prn:fleet:accounts:/64a1b2c3..." },
  "workspace": { "id": "64f7a8b9...", "nick": "highercomve", "is_own": false },
  "environment": { "id": "64d5e6f7...", "name": "production" },
  "available_environments": [
    { "id": "64d5e6f7...", "name": "production" },
    { "id": "64e8f9a0...", "name": "development" }
  ],
  "access_mode": "environment",
  "token": { "expires_at": "2026-04-06T15:30:00Z" }
}
FieldDescription
userThe authenticated user's identity.
workspace.is_owntrue if the user is on their own workspace.
environmentActive environment (empty if all).
available_environmentsAll environments in the active workspace.
access_modeOne of owner, workspace, environment_scoped, environment.
token.expires_atToken expiration in ISO 8601.

Access modes ​

ModeMeaning
ownerUser is on their own workspace with full access.
workspaceWhole-workspace guest access (all environments).
environment_scopedGuest access limited to specific environments.
environmentA specific environment is selected (token is environment-filtered).

Using the token ​

Include the token in the Authorization header:

GET {fleet_url}/api/v1/devices
Authorization: Bearer {access_token}

The server uses the workspace and environment claims to filter responses to the correct scope.

Expiration ​

  • Access tokens expire after a server-configured duration (see the exp claim and token.expires_at). There is no refresh token — restart the PKCE flow to get a new one.
  • Authorization codes expire 5 minutes after creation and can be used once. If the exchange fails, restart the flow.

Complete example (Python) ​

python
import hashlib
import base64
import secrets
import urllib.parse
import webbrowser
from http.server import HTTPServer, BaseHTTPRequestHandler
import requests

FLEET_URL = "https://fleet.example.com"
CLIENT_ID = "my-cli-app"
CALLBACK_PORT = 37727

# Step 1: Generate PKCE parameters
code_verifier = secrets.token_urlsafe(64)
code_challenge = base64.urlsafe_b64encode(
    hashlib.sha256(code_verifier.encode()).digest()
).decode().rstrip("=")
state = secrets.token_urlsafe(32)

# Step 2: Open browser
auth_url = (
    f"{FLEET_URL}/auth/authorize"
    f"?client_id={CLIENT_ID}"
    f"&redirect_uri=http://127.0.0.1:{CALLBACK_PORT}/callback"
    f"&code_challenge={code_challenge}"
    f"&code_challenge_method=S256"
    f"&state={state}"
)
webbrowser.open(auth_url)

# Step 7: Receive callback
auth_code = None
class CallbackHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global auth_code
        params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
        auth_code = params.get("code", [None])[0]
        received_state = params.get("state", [None])[0]
        assert received_state == state, "State mismatch!"
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"Login successful! You can close this tab.")

server = HTTPServer(("127.0.0.1", CALLBACK_PORT), CallbackHandler)
server.handle_request()

# Step 8: Exchange code for token
token_response = requests.post(f"{FLEET_URL}/api/v1/oauth2/token", data={
    "grant_type": "authorization_code",
    "client_id": CLIENT_ID,
    "redirect_uri": f"http://127.0.0.1:{CALLBACK_PORT}/callback",
    "code": auth_code,
    "code_verifier": code_verifier,
})
token_data = token_response.json()
access_token = token_data["access_token"]

# Use the token for API calls
devices = requests.get(
    f"{FLEET_URL}/api/v1/devices",
    headers={"Authorization": f"Bearer {access_token}"}
).json()