> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/QwenLM/qwen-code/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Configure Qwen OAuth or API key authentication to connect Qwen Code to AI providers

## Overview

Qwen Code supports two authentication methods, each suited for different use cases:

<CardGroup cols={2}>
  <Card title="Qwen OAuth" icon="shield-check">
    **Recommended for most users**

    * Sign in with your qwen.ai account
    * 1,000 free requests per day
    * No API key management required
    * Browser-based authentication flow
  </Card>

  <Card title="API Key" icon="key">
    **For advanced users and production**

    * Use your own API keys
    * Support for multiple providers
    * Full control over models and quotas
    * Works in headless environments
  </Card>
</CardGroup>

<Note>
  You can switch between authentication methods at any time using the `/auth` command.
</Note>

## Qwen OAuth (Recommended)

Qwen OAuth is the easiest way to get started with Qwen Code. Sign in once and get immediate access to AI-powered coding assistance.

### Features

* **Free tier**: 1,000 requests per day at no cost
* **No API keys**: No need to manage API keys or billing
* **Auto-refresh**: Credentials refresh automatically
* **Secure**: OAuth 2.0 standard with token encryption

### Setup

<Steps>
  <Step title="Launch Qwen Code">
    Start Qwen Code from your terminal:

    ```bash theme={null}
    qwen
    ```
  </Step>

  <Step title="Run auth command">
    Type the auth command:

    ```bash theme={null}
    qwen> /auth
    ```
  </Step>

  <Step title="Select Qwen OAuth">
    Choose **Qwen OAuth** from the authentication options menu.
  </Step>

  <Step title="Complete browser flow">
    1. A browser window opens automatically
    2. Sign in with your qwen.ai account (or create a new account)
    3. Authorize Qwen Code to access your account
    4. You'll be redirected to a success page
    5. Return to your terminal—authentication is complete!

    ```text theme={null}
    ✓ Authentication successful!
    ✓ Signed in as: your-email@example.com
    ✓ Free tier: 1,000 requests/day remaining
    ```
  </Step>
</Steps>

### Usage in Production

<Warning>
  **Qwen OAuth requires interactive browser access**. In non-interactive environments (CI/CD, Docker containers, SSH sessions without X11), use API key authentication instead.
</Warning>

Environments where OAuth **won't work**:

* Continuous Integration (CI/CD) pipelines
* Docker containers without display
* SSH sessions without X11 forwarding
* Headless servers
* Automated scripts

For these scenarios, use [API Key authentication](#api-key-authentication).

### Credential Storage

OAuth credentials are stored securely:

* **Location**: `~/.qwen/auth/oauth-tokens.json`
* **Encryption**: Tokens are encrypted at rest
* **Auto-refresh**: Access tokens refresh automatically before expiration
* **Privacy**: Never shared or sent to third parties

### Checking Your Usage

Check remaining requests at any time:

```bash theme={null}
qwen> /stats
```

Output:

```text theme={null}
Session Statistics
──────────────────────────────────────
Provider:        Qwen OAuth
Model:           qwen3.5-plus
Requests today:  247 / 1,000
Tokens used:     45,892
Session time:    1h 23m
```

### Signing Out

To sign out and clear credentials:

```bash theme={null}
qwen> /auth
# Select "Sign Out" or choose a different authentication method
```

Or manually remove credentials:

```bash theme={null}
rm -rf ~/.qwen/auth/
```

## API Key Authentication

API key authentication gives you full control over which AI provider and model to use. It's ideal for:

* Production deployments
* CI/CD pipelines
* Custom model configurations
* Team environments with shared API keys
* Users who want to use their own API quotas

### Supported Providers

Qwen Code supports multiple AI providers through API key authentication:

<Tabs>
  <Tab title="OpenAI-Compatible">
    **Providers**:

    * Alibaba Cloud Dashscope (Qwen models)
    * Alibaba Cloud Bailian Coding Plan
    * OpenAI (GPT models)
    * OpenRouter (multiple models)
    * Any OpenAI-compatible API

    **Required**:

    * API key
    * Base URL (if not using OpenAI directly)
    * Model ID
  </Tab>

  <Tab title="Anthropic">
    **Providers**:

    * Anthropic (Claude models)

    **Required**:

    * Anthropic API key
    * Base URL
    * Model ID (e.g., `claude-sonnet-4-20250514`)
  </Tab>

  <Tab title="Google GenAI">
    **Providers**:

    * Google Gemini (via GenAI API)
    * Vertex AI

    **Required**:

    * Google API key
    * Model ID (e.g., `gemini-2.5-pro`)
  </Tab>
</Tabs>

### Quick Setup with settings.json

The **recommended** way to configure API key authentication is using `~/.qwen/settings.json`:

<Steps>
  <Step title="Create settings file">
    Create or edit `~/.qwen/settings.json` in your home directory:

    ```bash theme={null}
    mkdir -p ~/.qwen
    nano ~/.qwen/settings.json
    ```
  </Step>

  <Step title="Add configuration">
    Example for Qwen models via Dashscope:

    ```json theme={null}
    {
      "modelProviders": {
        "openai": [
          {
            "id": "qwen3-coder-plus",
            "name": "qwen3-coder-plus",
            "baseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
            "description": "Qwen3-Coder via Dashscope",
            "envKey": "DASHSCOPE_API_KEY"
          }
        ]
      },
      "env": {
        "DASHSCOPE_API_KEY": "sk-xxxxxxxxxxxxx"
      },
      "security": {
        "auth": {
          "selectedType": "openai"
        }
      },
      "model": {
        "name": "qwen3-coder-plus"
      }
    }
    ```
  </Step>

  <Step title="Get your API key">
    * **Dashscope**: Get key from [Alibaba Cloud Dashscope](https://dashscope.console.aliyun.com/)
    * **OpenAI**: Get key from [OpenAI Platform](https://platform.openai.com/api-keys)
    * **Anthropic**: Get key from [Anthropic Console](https://console.anthropic.com/)
    * **Google**: Get key from [Google AI Studio](https://makersuite.google.com/app/apikey)
  </Step>

  <Step title="Start Qwen Code">
    ```bash theme={null}
    qwen
    ```

    Your configuration takes effect automatically.
  </Step>
</Steps>

### Configuration Fields

| Field                          | Description                                                                       |
| ------------------------------ | --------------------------------------------------------------------------------- |
| `modelProviders`               | Define available models per protocol (`openai`, `anthropic`, `gemini`)            |
| `modelProviders[].id`          | Model ID sent to the API (e.g., `qwen3-coder-plus`, `gpt-4o`)                     |
| `modelProviders[].name`        | Display name shown in model selection                                             |
| `modelProviders[].baseUrl`     | API endpoint URL (required for non-default endpoints)                             |
| `modelProviders[].envKey`      | Environment variable name that holds the API key                                  |
| `modelProviders[].description` | Optional description shown in model selection                                     |
| `env`                          | Fallback place to store API keys (prefer environment variables for security)      |
| `security.auth.selectedType`   | Default auth protocol: `openai`, `anthropic`, `gemini`, `vertex-ai`, `qwen-oauth` |
| `model.name`                   | Default model to use on startup                                                   |

### Example Configurations

<Accordion title="Alibaba Cloud Bailian Coding Plan">
  Higher quotas with a fixed monthly subscription:

  ```json theme={null}
  {
    "modelProviders": {
      "openai": [
        {
          "id": "qwen3.5-plus",
          "name": "qwen3.5-plus (Coding Plan)",
          "baseUrl": "https://coding.dashscope.aliyuncs.com/v1",
          "description": "qwen3.5-plus with thinking enabled",
          "envKey": "BAILIAN_CODING_PLAN_API_KEY",
          "generationConfig": {
            "extra_body": {
              "enable_thinking": true
            }
          }
        },
        {
          "id": "qwen3-coder-plus",
          "name": "qwen3-coder-plus (Coding Plan)",
          "baseUrl": "https://coding.dashscope.aliyuncs.com/v1",
          "envKey": "BAILIAN_CODING_PLAN_API_KEY"
        }
      ]
    },
    "env": {
      "BAILIAN_CODING_PLAN_API_KEY": "sk-xxxxxxxxxxxxx"
    },
    "security": {
      "auth": {
        "selectedType": "openai"
      }
    },
    "model": {
      "name": "qwen3-coder-plus"
    }
  }
  ```

  Get your API key from [Alibaba Cloud Bailian](https://modelstudio.console.aliyun.com/?tab=dashboard#/efm/coding_plan).
</Accordion>

<Accordion title="Multiple Providers (OpenAI + Anthropic + Gemini)">
  Configure multiple providers and switch between them:

  ```json theme={null}
  {
    "modelProviders": {
      "openai": [
        {
          "id": "gpt-4o",
          "name": "GPT-4o",
          "envKey": "OPENAI_API_KEY",
          "baseUrl": "https://api.openai.com/v1"
        }
      ],
      "anthropic": [
        {
          "id": "claude-sonnet-4-20250514",
          "name": "Claude Sonnet 4",
          "envKey": "ANTHROPIC_API_KEY",
          "baseUrl": "https://api.anthropic.com"
        }
      ],
      "gemini": [
        {
          "id": "gemini-2.5-pro",
          "name": "Gemini 2.5 Pro",
          "envKey": "GEMINI_API_KEY"
        }
      ]
    },
    "env": {
      "OPENAI_API_KEY": "sk-xxxxxxxxxxxxx",
      "ANTHROPIC_API_KEY": "sk-ant-xxxxxxxxxxxxx",
      "GEMINI_API_KEY": "AIzaxxxxxxxxxxxxx"
    },
    "security": {
      "auth": {
        "selectedType": "openai"
      }
    },
    "model": {
      "name": "gpt-4o"
    }
  }
  ```

  Switch between models during a session:

  ```bash theme={null}
  qwen> /model
  # Select from: GPT-4o, Claude Sonnet 4, Gemini 2.5 Pro
  ```
</Accordion>

<Accordion title="Enable Thinking Mode (qwen3.5-plus)">
  For supported models with extended reasoning:

  ```json theme={null}
  {
    "modelProviders": {
      "openai": [
        {
          "id": "qwen3.5-plus",
          "name": "qwen3.5-plus (thinking)",
          "envKey": "DASHSCOPE_API_KEY",
          "baseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
          "generationConfig": {
            "extra_body": {
              "enable_thinking": true
            }
          }
        }
      ]
    },
    "env": {
      "DASHSCOPE_API_KEY": "sk-xxxxxxxxxxxxx"
    },
    "security": {
      "auth": {
        "selectedType": "openai"
      }
    },
    "model": {
      "name": "qwen3.5-plus"
    }
  }
  ```
</Accordion>

### Environment Variables

For better security, set API keys via environment variables instead of storing them in `settings.json`:

<CodeGroup>
  ```bash Bash/Zsh theme={null}
  # Add to ~/.bashrc or ~/.zshrc
  export DASHSCOPE_API_KEY="sk-xxxxxxxxxxxxx"
  export OPENAI_API_KEY="sk-xxxxxxxxxxxxx"
  export ANTHROPIC_API_KEY="sk-ant-xxxxxxxxxxxxx"
  ```

  ```bash .env file theme={null}
  # Create .env in your project directory
  DASHSCOPE_API_KEY=sk-xxxxxxxxxxxxx
  OPENAI_API_KEY=sk-xxxxxxxxxxxxx
  ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxx
  ```

  ```bash One-time use theme={null}
  # Set for current session only
  DASHSCOPE_API_KEY=sk-xxxxxxxxxxxxx qwen
  ```
</CodeGroup>

<Warning>
  **Never commit API keys to version control**. Use environment variables or `.env` files (added to `.gitignore`).
</Warning>

### Priority Order

Qwen Code checks for API keys in this order (highest to lowest priority):

1. **Environment variables** (from your shell or `.env` file)
2. **Custom `envKey`** (defined in `modelProviders[].envKey`)
3. **settings.json `env` field** (fallback, lowest priority)

Example:

```json theme={null}
// In settings.json, define envKey
{
  "modelProviders": {
    "openai": [
      {
        "id": "qwen3-coder-plus",
        "envKey": "DASHSCOPE_API_KEY",  // Qwen Code will look for this env var
        ...
      }
    ]
  }
}
```

```bash theme={null}
# Set the environment variable
export DASHSCOPE_API_KEY="sk-xxxxxxxxxxxxx"
qwen
```

## Switching Authentication Methods

You can change authentication methods at any time:

<Steps>
  <Step title="Run /auth command">
    ```bash theme={null}
    qwen> /auth
    ```
  </Step>

  <Step title="Select new method">
    Choose from:

    * Qwen OAuth
    * OpenAI-compatible API
    * Anthropic API
    * Google GenAI
    * Vertex AI
  </Step>

  <Step title="Complete setup">
    Follow the prompts to configure the new authentication method.
  </Step>
</Steps>

## Project-Specific Configuration

Override global settings for specific projects by creating `.qwen/settings.json` in your project root:

```bash theme={null}
cd your-project/
mkdir .qwen
nano .qwen/settings.json
```

Project settings override global settings:

```json theme={null}
{
  "security": {
    "auth": {
      "selectedType": "anthropic"
    }
  },
  "model": {
    "name": "claude-sonnet-4-20250514"
  }
}
```

Now this project always uses Claude, while other projects use your global defaults.

<Tip>
  Use project-specific settings to configure different models for different types of projects (e.g., Claude for research, Qwen for coding).
</Tip>

## Validation

Qwen Code validates your authentication configuration on startup:

```text theme={null}
✓ Authentication: API Key (OpenAI-compatible)
✓ Model: qwen3-coder-plus
✓ Base URL: https://dashscope.aliyuncs.com/compatible-mode/v1
✓ API Key: Found (DASHSCOPE_API_KEY)
```

If validation fails, you'll see helpful error messages:

```text theme={null}
✗ Authentication failed
✗ DASHSCOPE_API_KEY environment variable not found

Please set the API key:
  export DASHSCOPE_API_KEY="your-api-key"

Or add it to ~/.qwen/settings.json
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="OAuth browser doesn't open">
    **Solutions**:

    1. Manually open the URL shown in the terminal
    2. Check if your `BROWSER` environment variable is set correctly
    3. Try running `qwen` from a different terminal emulator
    4. Use API key authentication in headless environments
  </Accordion>

  <Accordion title="API key not found">
    **Solutions**:

    1. Verify the environment variable name matches `envKey` in settings
    2. Check if the variable is exported: `echo $DASHSCOPE_API_KEY`
    3. Restart your terminal after adding to `.bashrc`/`.zshrc`
    4. Use absolute paths for `.env` files
  </Accordion>

  <Accordion title="Invalid API key error">
    **Solutions**:

    1. Verify the API key is correct (no extra spaces)
    2. Check if the key has expired
    3. Ensure you have sufficient quota/credits
    4. Verify the key has permissions for the model you're using
  </Accordion>

  <Accordion title="Wrong model provider">
    **Solutions**:

    1. Check `security.auth.selectedType` in settings.json
    2. Ensure the model ID matches the provider protocol
    3. Use `/model` to switch models during a session
    4. Verify `baseUrl` matches your provider's API endpoint
  </Accordion>

  <Accordion title="Rate limit exceeded">
    **Solutions**:

    1. For Qwen OAuth: Wait until your daily quota resets (midnight UTC)
    2. For API keys: Check your provider's rate limits
    3. Use `/compress` to reduce token usage
    4. Switch to a different model or provider with `/model`
  </Accordion>
</AccordionGroup>

## Security Best Practices

<CardGroup cols={2}>
  <Card title="Use Environment Variables" icon="shield">
    Store API keys in environment variables or `.env` files, never in `settings.json` committed to git.
  </Card>

  <Card title="Rotate Keys Regularly" icon="rotate">
    Rotate API keys periodically, especially after team member changes.
  </Card>

  <Card title="Limit Key Scope" icon="lock">
    Use API keys with minimal required permissions. Avoid admin or billing access.
  </Card>

  <Card title="Use .gitignore" icon="file-slash">
    Add `.env` and `settings.json` files containing secrets to `.gitignore`.
  </Card>
</CardGroup>

<Warning>
  The `~/.qwen/settings.json` file in your home directory should be kept private. Never commit it to version control.
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="Quick Start" icon="rocket" href="/quickstart">
    Complete your first AI-assisted coding session
  </Card>

  <Card title="Model Providers" icon="brain" href="/configuration/model-providers">
    Learn more about configuring multiple providers
  </Card>

  <Card title="Environment Variables" icon="terminal" href="/configuration/environment-variables">
    Full reference for environment variable configuration
  </Card>

  <Card title="Settings Reference" icon="gear" href="/configuration/settings">
    Complete settings.json documentation
  </Card>
</CardGroup>
