> ## Documentation Index
> Fetch the complete documentation index at: https://developer.kodexa.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Configure authentication for the kdx CLI in Kodexa using access tokens, profiles, or environment variables to connect to Kodexa environments.

# Authentication

The kdx CLI supports multiple authentication methods to connect to Kodexa environments.

## Authentication Methods

| Method                | Use Case                        |
| --------------------- | ------------------------------- |
| OAuth Login           | Interactive browser-based login |
| Device Code           | Headless/server environments    |
| API Key               | Automation and CI/CD            |
| Environment Variables | Container deployments           |

## OAuth Login (Recommended)

The `kdx login` command provides browser-based OAuth authentication.

```bash theme={null}
kdx login <url> [flags]
```

### Flags

| Flag           | Default   | Description                                |
| -------------- | --------- | ------------------------------------------ |
| `--profile`    | `default` | Profile name to save credentials           |
| `--device`     | `false`   | Use device-code flow (no browser)          |
| `--no-browser` | `false`   | Print login URL instead of opening browser |
| `--timeout`    | `180`     | Seconds to wait for login completion       |

### Examples

```bash theme={null}
# Login to production
kdx login https://app.kodexa.com --profile prod

# Login to demo environment
kdx login https://demo.kodexa-enterprise.com --profile demo

# Login to development environment
kdx login https://dev.kodexa-enterprise.com --profile dev
```

### How It Works

1. CLI opens your default browser to the Kodexa login page
2. You authenticate with your credentials
3. Browser redirects back to CLI with authentication token
4. CLI saves the token to your profile

```
Opening browser for authentication...
✓ Successfully authenticated
Profile 'demo' saved to ~/.kodexa/config.yaml
```

## Device Code Flow

For environments without a browser (servers, containers, SSH sessions), use device-code authentication:

```bash theme={null}
kdx login https://app.kodexa.com --device --profile server
```

### How It Works

1. CLI displays a code and URL
2. You visit the URL on any device and enter the code
3. CLI polls for completion and saves the token

```
To authenticate, visit: https://app.kodexa.com/device
Enter code: ABCD-1234

Waiting for authentication...
✓ Successfully authenticated
Profile 'server' saved
```

## API Key Authentication

For automation and CI/CD, you can use API keys directly.

### Creating an API Key

1. Log in to your Kodexa environment
2. Navigate to **Settings** → **API Keys**
3. Click **Create API Key**
4. Copy the generated key (shown only once)

### Using API Keys

#### Option 1: Save to Profile

```bash theme={null}
# Add API key to config manually
kdx config set-profile myenv \
  --url https://app.kodexa.com \
  --api-key kdx_pat_xxxxx
```

#### Option 2: Command Line Flag

```bash theme={null}
kdx --api-key kdx_pat_xxxxx get projects
```

#### Option 3: Environment Variables

```bash theme={null}
export KODEXA_URL=https://app.kodexa.com
export KODEXA_ACCESS_TOKEN=kdx_pat_xxxxx

kdx get projects
```

## Environment Variables

For containerized deployments and CI/CD, environment variables provide flexible authentication:

| Variable              | Description            |
| --------------------- | ---------------------- |
| `KODEXA_URL`          | Kodexa platform URL    |
| `KODEXA_ACCESS_TOKEN` | API key or OAuth token |

### Example: GitHub Actions

```yaml theme={null}
jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      KODEXA_URL: ${{ secrets.KODEXA_URL }}
      KODEXA_ACCESS_TOKEN: ${{ secrets.KODEXA_TOKEN }}
    steps:
      - uses: actions/checkout@v4
      - name: Deploy resources
        run: kdx sync deploy ./resources
```

### Example: Docker

```dockerfile theme={null}
FROM alpine:latest

# Install kdx
RUN curl -L https://github.com/kodexa-ai/kodexa-cli/releases/latest/download/kdx-linux-amd64 -o /usr/local/bin/kdx \
    && chmod +x /usr/local/bin/kdx

# Set environment variables at runtime
ENV KODEXA_URL=""
ENV KODEXA_ACCESS_TOKEN=""

CMD ["kdx", "get", "projects"]
```

```bash theme={null}
docker run -e KODEXA_URL=https://app.kodexa.com \
           -e KODEXA_ACCESS_TOKEN=kdx_pat_xxxxx \
           my-kdx-image
```

## Profile Configuration

Profiles store authentication credentials locally for easy switching between environments.

### Profile Location

Credentials are stored in `~/.kodexa/config.yaml`:

```yaml theme={null}
currentprofile: demo
profiles:
  demo:
    name: demo
    url: https://demo.kodexa-enterprise.com
    apiKey: kdx_pat_xxxxx
  prod:
    name: prod
    url: https://app.kodexa.com
    apiKey: kdx_pat_yyyyy
```

### Managing Profiles

```bash theme={null}
# List profiles
kdx config list-profiles

# Switch profile
kdx config use-profile prod

# Show current profile
kdx config current-profile

# Delete profile
kdx config delete-profile old-env

# Use specific profile for single command
kdx --profile demo get projects
```

## Authentication Priority

When multiple authentication methods are configured, kdx uses this priority:

1. `--api-key` command line flag
2. `--profile` command line flag
3. `KODEXA_ACCESS_TOKEN` environment variable
4. Current profile in config file

## Security Best Practices

### API Key Security

* **Never commit API keys** to version control
* Use **environment variables** in CI/CD
* **Rotate keys** periodically
* Use **minimal permissions** for automation keys

### Profile Security

* Profile config is stored with user-only permissions (`600`)
* Consider using **credential helpers** for sensitive environments
* Use **separate profiles** for production vs development

### Token Expiration

* OAuth tokens may expire; re-run `kdx login` to refresh
* API keys don't expire unless revoked
* Check token validity with `kdx get projects` (quick test)

## Troubleshooting

### Authentication Failed

```
Error: authentication failed: invalid credentials
```

**Solutions**:

* Verify the URL is correct
* Check if API key is valid and not revoked
* Try `kdx login` to refresh OAuth token

### Profile Not Found

```
Error: profile 'myenv' not found
```

**Solutions**:

* List profiles with `kdx config list-profiles`
* Create profile with `kdx login` or `kdx config set-profile`

### Browser Doesn't Open

```
Error: failed to open browser
```

**Solutions**:

* Use `--no-browser` flag and open URL manually
* Use `--device` flag for device-code flow
* Check if `xdg-open` (Linux) or `open` (macOS) is available

## Automatic Re-Authentication

When the CLI encounters a **401 Unauthorized** response during any operation, it automatically prompts you to re-authenticate instead of failing with an error. This is useful when OAuth tokens expire during a long session.

```
⚠ Authentication expired. Re-authenticate now? (Y/n)
Opening browser for authentication...
✓ Successfully re-authenticated
Retrying operation...
```

The CLI will:

1. Detect the 401 response
2. Prompt you to re-authenticate (skipped during non-interactive/CI usage)
3. Open the browser for OAuth login (or use device code flow if configured)
4. Retry the original operation with the new token

<Note>
  Automatic re-authentication is skipped during startup plugin discovery to avoid interrupting CLI initialization.
</Note>

### Timeout During Login

```
Error: login timeout after 180 seconds
```

**Solutions**:

* Increase timeout with `--timeout 300`
* Ensure you complete browser authentication before timeout
* Check network connectivity to Kodexa server
