Fix clw-auth-disconnected: Authentication Session Lost or Connection Terminated

OpenClaw intermediate macOS Linux Windows Cross-platform

1. Symptoms

When the clw-auth-disconnected error occurs, users typically encounter one or more of the following symptoms:

Terminal Output

$ claw connect --project my-app
Error: clw-auth-disconnected
Authentication session lost. Please re-authenticate to continue.

$ claw status
✗ Connection lost - clw-auth-disconnected
  Session expired at: 2024-01-15T10:30:00Z

$ claw deploy --env production
[ERROR] clw-auth-disconnected
Remote authentication server closed the connection unexpectedly.
Operation aborted.
---

### Behavioral Symptoms

- **Sudden disconnection** during active CLI operations
- **Inability to execute authenticated commands** without re-authentication
- **Session status shows disconnected** even though network appears functional
- **Commands timeout** or fail with authentication-related messages
- **Background sync operations** fail silently or report disconnection

### Common Scenarios Where Error Appears

| Scenario | Frequency | Recovery Time |
|----------|-----------|---------------|
| Network interruption | High | 30-60 seconds |
| Idle session timeout | Medium | Immediate |
| Server-side session revocation | Low | 5-10 minutes |
| Token expiration mid-operation | High | Immediate |

---

## 2. Root Cause

The `clw-auth-disconnected` error stems from several potential root causes, each related to the breakdown of the authentication session between the OpenClaw client and the authentication server.

### Primary Causes

**1. Network Interruption During Active Session**

The most common cause is a network disruption that severs the connection between the client and authentication server. This can occur due to:
- WiFi or ethernet disconnection
- VPN tunnel instability
- Firewall or proxy interference
- DNS resolution failures

**2. Server-Side Session Invalidation**

The authentication server may invalidate sessions for various reasons:
- Security policy triggers (suspicious activity detection)
- Concurrent session limits exceeded
- Administrative session revocation
- Server-side maintenance or restart

**3. Token Expiration Without Grace Period**

OpenClaw uses bearer tokens for authentication. When tokens expire:

Token issued: 2024-01-15T09:00:00Z Token expires: 2024-01-15T10:00:00Z Actual request: 2024-01-15T10:05:00Z Result: clw-auth-disconnected


**4. Client-Side Configuration Issues**

Misconfigurations that lead to disconnection:
- Incorrect authentication endpoint URL
- Expired or revoked client credentials
- Corrupted local session cache
- Clock skew causing premature token rejection

**5. Idle Timeout Triggers**

Many authentication servers implement idle timeouts:
```bash
# Default idle timeout: 30 minutes
# Session becomes invalid after 30 minutes of inactivity
# Next command triggers clw-auth-disconnected

Technical Flow

┌─────────────┐     Authentication      ┌─────────────────┐
│   Client    │ ◄─────────────────────► │ Auth Server     │
│  (OpenClaw) │                        │                 │
└─────────────┘                        └─────────────────┘
       │                                       │
       │ 1. POST /auth/login                   │ 2. Validate
       │ 2. Receive session token              │    credentials
       │ 3. Store in local cache               │ 3. Generate
       │                                       │    session token
       │                                       │
       ▼                                       ▼
┌─────────────────────────────────────────────────────────┐
│ Session Active: All commands use session token in       │
│ Authorization header                                     │
└─────────────────────────────────────────────────────────┘
       ▼ [Connection Lost / Token Invalid / Session Revoked]
┌─────────────────────────────────────────────────────────┐
│ Error: clw-auth-disconnected                            │
│ Message: "Authentication session lost"                 │
└─────────────────────────────────────────────────────────┘

3. Step-by-Step Fix

Method 1: Re-authenticate (Quick Fix)

This is the fastest resolution for most cases.

Step 1: Check Current Auth Status

# Verify the disconnection
claw auth status

# Expected output before fix
# Status: Disconnected
# Last connected: 2024-01-15T09:45:00Z
# Error: clw-auth-disconnected

Step 2: Clear Local Session Cache

# Remove stale session data
claw auth logout --force

# Verify cache cleared
claw auth status
# Status: Logged out

Step 3: Re-authenticate

# Interactive authentication
claw auth login

# Non-interactive authentication (CI/CD environments)
claw auth login --token $OPENCLAW_API_TOKEN

Step 4: Verify Reconnection

# Confirm authentication restored
claw auth status

# Expected output
# Status: Connected
# User: [email protected]
# Session expires: 2024-01-15T11:00:00Z

Method 2: Fix Network Configuration Issues

If network instability is the root cause:

Before:

# This may fail with clw-auth-disconnected
claw connect --project my-app

# Check current DNS configuration
cat /etc/resolv.conf
# nameserver 8.8.8.8

After:

# Configure stable DNS servers
sudo tee /etc/resolv.conf > /dev/null <<EOF
nameserver 1.1.1.1
nameserver 8.8.8.8
options timeout:2 attempts:3
EOF

# Test network stability
ping -c 10 auth.openclaw.io

# Retry connection
claw connect --project my-app

Method 3: Configure Persistent Sessions (Long-term Fix)

Before:

# Default: sessions expire after 1 hour of inactivity
# Environment: default (no persistent sessions)

# Operations fail after idle period
claw deploy --env staging
# Error: clw-auth-disconnected

After:

# Configure persistent sessions
claw config set auth.session.persist true
claw config set auth.session.timeout 7200  # 2 hours
claw config set auth.retry.enabled true
claw config set auth.retry.max_attempts 3

# Verify configuration
claw config get auth

# Output:
# session.persist: true
# session.timeout: 7200
# retry.enabled: true
# retry.max_attempts: 3

Method 4: Fix Token-based Authentication (CI/CD)

Before:

# .claw.yaml (broken configuration)
auth:
  token: ${CLAW_TOKEN}
  endpoint: https://api.openclaw.io/v1
  # Missing: token refresh configuration

After:

# .claw.yaml (corrected configuration)
auth:
  token: ${CLAW_TOKEN}
  endpoint: https://api.openclaw.io/v1
  token_refresh_threshold: 300  # Refresh 5 min before expiry
  auto_refresh: true
  retry_on_disconnect: true
  max_retries: 3

Method 5: Debug and Diagnose Connection Issues

# Enable verbose logging for diagnosis
claw --verbose auth status

# Output with verbose mode
# [DEBUG] Checking auth server: https://auth.openclaw.io
# [DEBUG] Connection attempt 1/3
# [DEBUG] TCP connection established
# [DEBUG] TLS handshake completed
# [DEBUG] Sending authentication request
# [ERROR] clw-auth-disconnected
# [DEBUG] Server response: Session terminated

# Check OpenClaw diagnostic info
claw doctor

# Verify API endpoint accessibility
curl -v https://auth.openclaw.io/health

4. Verification

After applying fixes, verify the error is resolved through the following checks:

Basic Verification

# 1. Check authentication status
claw auth status

# Expected output:
# ✓ Authenticated: [email protected]
# ✓ Session valid until: 2024-01-15T12:00:00Z
# ✓ Connection: Stable

Functional Verification

# 2. Test command execution
claw projects list

# Expected: List of projects returned without error

# 3. Test file operations
claw sync --dry-run

# Expected: Sync preview completes successfully

# 4. Test deployment (staging only)
claw deploy --env staging --dry-run

# Expected: Deployment plan generated

Long-term Stability Test

# 5. Monitor for 5 minutes
claw monitor --duration 300

# Expected output:
# [10:00:00] Connection stable
# [10:01:00] Connection stable
# [10:02:00] Connection stable
# ...
# [10:05:00] No clw-auth-disconnected errors detected

Automated Verification Script

#!/bin/bash
# verify-fix.sh - Automated verification script

echo "Running authentication verification..."

# Test 1: Auth status
STATUS=$(claw auth status --json 2>/dev/null)
if echo "$STATUS" | grep -q "connected"; then
    echo "✓ Authentication status: PASS"
else
    echo "✗ Authentication status: FAIL"
    exit 1
fi

# Test 2: Command execution
if claw projects list --quiet 2>/dev/null; then
    echo "✓ Command execution: PASS"
else
    echo "✗ Command execution: FAIL"
    exit 1
fi

# Test 3: Session persistence
sleep 5
if claw auth status --json 2>/dev/null | grep -q "connected"; then
    echo "✓ Session persistence: PASS"
else
    echo "✗ Session persistence: FAIL"
    exit 1
fi

echo "All verification tests passed!"

5. Common Pitfalls

Pitfall 1: Ignoring Token Expiration in Scripts

Problem: Scripts fail hours after authentication due to token expiration.

# WRONG: Token hardcoded in script
CLAW_TOKEN="eyJhbGc..."  # Expires in 1 hour

claw deploy --env production
# Works initially, fails after 1 hour with clw-auth-disconnected

Solution: Use environment variables with automatic refresh.

# CORRECT: Use environment variable that gets refreshed
export OPENCLAW_TOKEN=$(claw auth token --refresh)
claw deploy --env production

Pitfall 2: Not Checking Network Before Re-authenticating

Problem: Re-authentication fails repeatedly due to underlying network issue.

# WRONG: Blindly re-authenticating
claw auth logout
claw auth login --token $TOKEN
# Repeatedly fails - didn't check network first

Solution: Diagnose network before authentication attempts.

# CORRECT: Check network first
ping -c 3 auth.openclaw.io || { echo "Network issue detected"; exit 1; }
claw auth login --token $TOKEN

Pitfall 3: Clearing Cache When It’s Not the Problem

Problem: Aggressively clearing session cache when the issue is server-side.

# WRONG: Over-clearing cache
claw auth logout --force
claw auth logout --all-sessions
rm -rf ~/.claw/sessions
# Still fails - server is down

Solution: Check server status before local interventions.

# CORRECT: Check server status
curl -s https://status.openclaw.io | grep "All Systems Operational"
# If server issue: wait or contact support
# If server OK: proceed with local fixes

Pitfall 4: Using Expired Tokens in CI/CD

Problem: CI/CD pipelines fail after token rotation.

# WRONG: Static token in CI config
# .gitlab-ci.yml
variables:
  OPENCLAW_TOKEN: "static-token-from-yesterday"

Solution: Use dynamic token retrieval.

# CORRECT: Dynamic token retrieval in CI
# .gitlab-ci.yml
before_script:
  - export OPENCLAW_TOKEN=$(vault read -field=token secret/openclaw/prod)
  - claw auth login --token $OPENCLAW_TOKEN

Pitfall 5: Not Setting Appropriate Timeout Values

Problem: Commands timeout and trigger disconnect errors for legitimate long operations.

# WRONG: Default timeout too short for large operations
claw sync --project huge-repo
# Fails after 30 seconds with clw-auth-disconnected

Solution: Configure appropriate timeouts.

# CORRECT: Increase timeout for large operations
claw config set connection.timeout 300
claw sync --project huge-repo

The following errors are commonly related to clw-auth-disconnected:

Error Code Description Relationship
clw-auth-expired Authentication token has expired Precedes or follows clw-auth-disconnected; same resolution path
clw-conn-timeout Connection attempt timed out Often triggers clw-auth-disconnected when timeout occurs during auth
clw-auth-invalid Credentials or token are invalid Different root cause but similar symptoms; different fix required
clw-session-terminated Session was explicitly terminated Similar to clw-auth-disconnected but indicates intentional termination
clw-network-unreachable Cannot reach authentication server Often co-occurs with clw-auth-disconnected; network must be fixed first
clw-auth-revoked Session was revoked by administrator Requires admin intervention; cannot be fixed by user alone
clw-token-invalid JWT or bearer token is malformed Similar symptoms but caused by corrupted tokens
clw-auth-challenge Additional authentication required Related multi-factor or step-up authentication scenario

Error Resolution Hierarchy

clw-auth-disconnected
├── Network issue → Fix network, then re-authenticate
│   └── Related: clw-network-unreachable, clw-conn-timeout
├── Token issue → Refresh or regenerate token
│   ├── Related: clw-auth-expired, clw-token-invalid
│   └── Fix: claw auth refresh
├── Session issue → Logout and login again
│   ├── Related: clw-session-terminated, clw-auth-revoked
│   └── Fix: claw auth logout && claw auth login
└── Server issue → Wait or contact support
    └── Related: Any auth error persisting after local fixes

Cross-Reference Quick Reference

  • If you see clw-auth-expired: Token expired; use claw auth refresh
  • If you see clw-conn-timeout: Network issue; check firewall and DNS
  • If you see clw-auth-invalid: Wrong credentials; verify and update
  • If you see clw-session-terminated: Server-side termination; re-authenticate
  • If you see clw-network-unreachable: Network config issue; fix connectivity first