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

# Authentication

> Authentication methods for the Open WebUI API

# Authentication

Open WebUI supports multiple authentication methods to secure API access. Choose the method that best fits your use case.

## Authentication Methods

### 1. JWT Token Authentication

JSON Web Tokens (JWT) are the primary authentication method for user sessions. Tokens are obtained by signing in and included in the `Authorization` header.

#### Obtaining a JWT Token

Sign in using the `/api/v1/auths/signin` endpoint:

```bash theme={null}
curl -X POST http://localhost:8080/api/v1/auths/signin \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "your_password"
  }'
```

**Response:**

```json theme={null}
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_at": 1735689600,
  "id": "user-uuid",
  "email": "user@example.com",
  "name": "John Doe",
  "role": "user",
  "profile_image_url": "/api/v1/users/user-uuid/profile/image",
  "permissions": {}
}
```

<ParamField body="email" type="string" required>
  User's email address
</ParamField>

<ParamField body="password" type="string" required>
  User's password
</ParamField>

#### Using JWT Tokens

Include the token in the `Authorization` header with the `Bearer` scheme:

```bash theme={null}
curl http://localhost:8080/api/v1/chats \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```

<Info>
  JWT tokens are signed using the `WEBUI_SECRET_KEY` environment variable with the HS256 algorithm.
</Info>

#### Token Expiration

Tokens expire based on the `JWT_EXPIRES_IN` configuration (default: `-1` for no expiration):

* `-1`: Never expires
* `0`: Expires immediately (single use)
* Duration string: `30m`, `2h`, `7d`, `4w` (minutes, hours, days, weeks)

**Token Response Fields:**

<ResponseField name="token" type="string">
  The JWT token string
</ResponseField>

<ResponseField name="token_type" type="string">
  Always "Bearer"
</ResponseField>

<ResponseField name="expires_at" type="integer">
  Unix timestamp when the token expires (null if never expires)
</ResponseField>

#### Token Revocation

Tokens can be revoked by signing out:

```bash theme={null}
curl -X GET http://localhost:8080/api/v1/auths/signout \
  -H "Authorization: Bearer {token}"
```

<Note>
  Token revocation requires Redis. Revoked tokens are stored with TTL matching the token expiration.
</Note>

### 2. API Key Authentication

API keys provide non-expiring authentication suitable for programmatic access and integrations.

#### Generating an API Key

Create an API key for your user account:

```bash theme={null}
curl -X POST http://localhost:8080/api/v1/auths/api_key \
  -H "Authorization: Bearer {jwt_token}"
```

**Response:**

```json theme={null}
{
  "api_key": "sk-1234567890abcdef1234567890abcdef"
}
```

<Warning>
  API keys are only shown once upon creation. Store them securely. If lost, delete and create a new key.
</Warning>

#### Using API Keys

API keys use the same `Authorization` header format as JWT tokens:

```bash theme={null}
curl http://localhost:8080/api/v1/models \
  -H "Authorization: Bearer sk-1234567890abcdef1234567890abcdef"
```

<Info>
  API keys are prefixed with `sk-` to distinguish them from JWT tokens.
</Info>

#### API Key Requirements

* API keys must be enabled globally: `ENABLE_API_KEYS=true`
* Users need the `features.api_keys` permission (admins have this by default)
* Each user can have one active API key at a time

#### Retrieving Your API Key

Get your current API key:

```bash theme={null}
curl http://localhost:8080/api/v1/auths/api_key \
  -H "Authorization: Bearer {jwt_token}"
```

#### Deleting an API Key

Revoke your API key:

```bash theme={null}
curl -X DELETE http://localhost:8080/api/v1/auths/api_key \
  -H "Authorization: Bearer {jwt_token}"
```

#### API Key Endpoint Restrictions

Administrators can restrict API keys to specific endpoints:

```bash theme={null}
# Environment configuration
ENABLE_API_KEYS_ENDPOINT_RESTRICTIONS=true
API_KEYS_ALLOWED_ENDPOINTS=/api/v1/chat,/api/v1/models,/api/v1/generate
```

When restrictions are enabled:

* JWT tokens have full access to all endpoints
* API keys can only access whitelisted endpoints
* Attempting to access a restricted endpoint returns `403 Forbidden`

### 3. OAuth 2.0 / OpenID Connect

Open WebUI supports OAuth 2.0 and OpenID Connect for SSO with external providers.

#### Supported Providers

* Google
* Microsoft Azure AD
* GitHub
* Generic OpenID Connect providers
* Custom OAuth providers

#### OAuth Configuration

Configure OAuth providers via environment variables or the admin panel:

```python theme={null}
OAUTH_PROVIDERS = {
  "google": {
    "client_id": "your-client-id.apps.googleusercontent.com",
    "client_secret": "your-client-secret",
    "server_metadata_url": "https://accounts.google.com/.well-known/openid-configuration",
    "scope": "openid email profile"
  }
}
```

#### OAuth Flow

1. Redirect user to `/oauth/{provider}/login`
2. User authenticates with the provider
3. Provider redirects to callback URL with authorization code
4. Open WebUI exchanges code for tokens
5. User is authenticated and receives a JWT token

#### OAuth Claims Mapping

Customize how user data is extracted from OAuth tokens:

<ParamField path="OAUTH_EMAIL_CLAIM" type="string" default="email">
  Claim containing the user's email address
</ParamField>

<ParamField path="OAUTH_USERNAME_CLAIM" type="string" default="name">
  Claim containing the user's display name
</ParamField>

<ParamField path="OAUTH_PICTURE_CLAIM" type="string" default="picture">
  Claim containing the user's profile image URL
</ParamField>

#### Role-Based Access with OAuth

Map OAuth roles to Open WebUI roles:

```bash theme={null}
ENABLE_OAUTH_ROLE_MANAGEMENT=true
OAUTH_ROLES_CLAIM=roles
OAUTH_ALLOWED_ROLES=user,admin,developer
OAUTH_ADMIN_ROLES=admin,super_admin
```

* Users with roles in `OAUTH_ADMIN_ROLES` become admins
* Users must have a role in `OAUTH_ALLOWED_ROLES` to access the system
* Users without allowed roles are denied access

#### Account Merging

Merge OAuth accounts with existing email accounts:

```bash theme={null}
OAUTH_MERGE_ACCOUNTS_BY_EMAIL=true
```

When enabled, signing in with OAuth links to existing accounts with matching email addresses.

#### Token Exchange (Advanced)

Exchange OAuth access tokens for Open WebUI JWT tokens:

```bash theme={null}
ENABLE_OAUTH_TOKEN_EXCHANGE=true
```

```bash theme={null}
curl -X POST http://localhost:8080/api/v1/auths/oauth/google/token/exchange \
  -H "Content-Type: application/json" \
  -d '{
    "token": "{oauth_access_token}"
  }'
```

<Warning>
  Token exchange is disabled by default. Enable only when needed for external integrations.
</Warning>

### 4. LDAP Authentication

Authenticate users against LDAP/Active Directory servers.

#### LDAP Configuration

Configure LDAP via environment variables or admin panel:

```bash theme={null}
ENABLE_LDAP=true
LDAP_SERVER_HOST=ldap.example.com
LDAP_SERVER_PORT=389
LDAP_SEARCH_BASE=dc=example,dc=com
LDAP_APP_DN=cn=admin,dc=example,dc=com
LDAP_APP_PASSWORD=admin_password
LDAP_ATTRIBUTE_FOR_MAIL=mail
LDAP_ATTRIBUTE_FOR_USERNAME=uid
LDAP_USE_TLS=true
```

#### LDAP Sign-In

Authenticate with LDAP credentials:

```bash theme={null}
curl -X POST http://localhost:8080/api/v1/auths/ldap \
  -H "Content-Type: application/json" \
  -d '{
    "user": "jdoe",
    "password": "ldap_password"
  }'
```

<ParamField body="user" type="string" required>
  LDAP username (value of LDAP\_ATTRIBUTE\_FOR\_USERNAME)
</ParamField>

<ParamField body="password" type="string" required>
  LDAP password
</ParamField>

**Response:** Same format as JWT sign-in (token, user details, etc.)

#### LDAP Group Synchronization

Automatically sync LDAP groups to Open WebUI groups:

```bash theme={null}
ENABLE_LDAP_GROUP_MANAGEMENT=true
ENABLE_LDAP_GROUP_CREATION=true
LDAP_ATTRIBUTE_FOR_GROUPS=memberOf
```

When enabled:

* Groups from `memberOf` attribute are synced on each login
* New groups are created if `ENABLE_LDAP_GROUP_CREATION=true`
* User group memberships are updated to match LDAP

### 5. Trusted Header Authentication

Delegate authentication to a reverse proxy or SSO gateway.

#### Configuration

```bash theme={null}
WEBUI_AUTH_TRUSTED_EMAIL_HEADER=X-Forwarded-Email
WEBUI_AUTH_TRUSTED_NAME_HEADER=X-Forwarded-User
WEBUI_AUTH_TRUSTED_GROUPS_HEADER=X-Forwarded-Groups
```

<Warning>
  Only use trusted headers behind a properly configured reverse proxy. Never expose this to the public internet.
</Warning>

#### How It Works

1. Reverse proxy authenticates the user
2. Proxy forwards user identity in HTTP headers
3. Open WebUI trusts these headers and creates/authenticates the user
4. Groups are synced if `WEBUI_AUTH_TRUSTED_GROUPS_HEADER` is set

#### Example Configuration (Nginx)

```nginx theme={null}
location / {
  proxy_set_header X-Forwarded-Email $remote_user;
  proxy_set_header X-Forwarded-User $http_x_forwarded_user;
  proxy_pass http://open-webui:8080;
}
```

## Authentication Error Codes

| Status | Error                                         | Description                                |
| ------ | --------------------------------------------- | ------------------------------------------ |
| `401`  | `Invalid credentials`                         | Incorrect email/password                   |
| `401`  | `Invalid token`                               | JWT token is malformed or expired          |
| `401`  | `Not authenticated`                           | No authentication provided                 |
| `403`  | `API key not allowed`                         | API keys disabled or user lacks permission |
| `403`  | `API key not allowed to access this endpoint` | Endpoint restriction enabled               |
| `403`  | `Access prohibited`                           | User role insufficient for operation       |
| `429`  | `Rate limit exceeded`                         | Too many sign-in attempts                  |

## Security Best Practices

<Check>
  **Do:**

  * Use HTTPS in production to encrypt tokens in transit
  * Store API keys securely (environment variables, secrets manager)
  * Rotate API keys periodically
  * Use short-lived JWT tokens for interactive sessions
  * Enable Redis for token revocation
  * Implement endpoint restrictions for API keys
  * Use OAuth for SSO and centralized user management
</Check>

<Warning>
  **Don't:**

  * Commit API keys or secrets to version control
  * Share API keys between users or applications
  * Use trusted header authentication without a reverse proxy
  * Disable authentication in production (`WEBUI_AUTH=false`)
  * Expose API keys in client-side code or URLs
</Warning>

## Code Examples

### Python

```python theme={null}
import requests

# Sign in and get JWT token
response = requests.post(
    "http://localhost:8080/api/v1/auths/signin",
    json={
        "email": "user@example.com",
        "password": "password123"
    }
)
data = response.json()
token = data["token"]

# Use token for authenticated requests
headers = {"Authorization": f"Bearer {token}"}
chats = requests.get(
    "http://localhost:8080/api/v1/chats",
    headers=headers
).json()

print(f"Retrieved {len(chats)} chats")
```

### JavaScript (Node.js)

```javascript theme={null}
const axios = require('axios');

const BASE_URL = 'http://localhost:8080/api/v1';

// Sign in
async function signIn(email, password) {
  const response = await axios.post(`${BASE_URL}/auths/signin`, {
    email,
    password
  });
  return response.data.token;
}

// Use API with token
async function getChats(token) {
  const response = await axios.get(`${BASE_URL}/chats`, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  return response.data;
}

// Example usage
(async () => {
  const token = await signIn('user@example.com', 'password123');
  const chats = await getChats(token);
  console.log(`Retrieved ${chats.length} chats`);
})();
```

### cURL

```bash theme={null}
# Sign in and extract token
TOKEN=$(curl -s -X POST http://localhost:8080/api/v1/auths/signin \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"password123"}' \
  | jq -r '.token')

# Use token for requests
curl http://localhost:8080/api/v1/chats \
  -H "Authorization: Bearer $TOKEN"
```

## Next Steps

<CardGroup cols={2}>
  <Card title="API Endpoints" icon="list" href="/api/endpoints">
    Explore available API endpoints
  </Card>

  <Card title="User Management" icon="users" href="/api/users">
    Manage users and permissions
  </Card>
</CardGroup>
