Merge pull request #683 from open-webui/oauth-manager

Oauth manager Re: #17210
This commit is contained in:
Classic298
2025-09-08 18:40:25 +02:00
committed by GitHub
3 changed files with 80 additions and 0 deletions

View File

@@ -65,9 +65,52 @@ Below is a list of optional arguments your tools can depend on:
- `__messages__`: List of previous messages
- `__files__`: Attached files
- `__model__`: A dictionary with model information
- `__oauth_token__`: A dictionary containing the user's valid, automatically refreshed OAuth token payload. This is the **new, recommended, and secure** way to access user tokens for making authenticated API calls. The dictionary typically contains `access_token`, `id_token`, and other provider-specific data.
For more information about `__oauth_token__` and how to configure this token to be sent to tools, check out the OAuth section in the [environment variable docs page](https://docs.openwebui.com/getting-started/env-configuration/) and the [SSO documentation](https://docs.openwebui.com/features/sso/).
Just add them as argument to any method of your Tool class just like `__user__` in the example above.
#### Using the OAuth Token in a Tool
When building tools that need to interact with external APIs on the user's behalf, you can now directly access their OAuth token. This removes the need for fragile cookie scraping and ensures the token is always valid.
**Example:** A tool that calls an external API using the user's access token.
```python
import httpx
from typing import Optional
class Tools:
# ... other class setup ...
async def get_user_profile_from_external_api(self, __oauth_token__: Optional[dict] = None) -> str:
"""
Fetches user profile data from a secure external API using their OAuth access token.
:param __oauth_token__: Injected by Open WebUI, contains the user's token data.
"""
if not __oauth_token__ or "access_token" not in __oauth_token__:
return "Error: User is not authenticated via OAuth or token is unavailable."
access_token = __oauth_token__["access_token"]
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
try:
async with httpx.AsyncClient() as client:
response = await client.get("https://api.my-service.com/v1/profile", headers=headers)
response.raise_for_status() # Raise an exception for bad status codes
return f"API Response: {response.json()}"
except httpx.HTTPStatusError as e:
return f"Error: Failed to fetch data from API. Status: {e.response.status_code}"
except Exception as e:
return f"An unexpected error occurred: {e}"
```
### Event Emitters
Event Emitters are used to add additional information to the chat interface. Similarly to Filter Outlets, Event Emitters are capable of appending content to the chat. Unlike Filter Outlets, they are not capable of stripping information. Additionally, emitters can be activated at any stage during the Tool.

View File

@@ -39,6 +39,23 @@ You cannot have Microsoft **and** Google as providers simultaneously.
| `OAUTH_UPDATE_PICTURE_ON_LOGIN` | `true` | Update user profile pictures from OAuth provider with each login. |
| `OAUTH_PICTURE_CLAIM` | `picture` | Field in the claim containing the profile picture. Set to empty string to disable picture updates (users receive default icon). |
| `WEBUI_AUTH_SIGNOUT_REDIRECT_URL` | *empty* | Redirect users to this URL after signout. E.g., `https://your-company.com/logout-success` |
| `OAUTH_SESSION_TOKEN_ENCRYPTION_KEY` | `WEBUI_SECRET_KEY` | **Required.** A secret key for encrypting OAuth tokens stored on the server. Must be shared across all instances in a cluster. |
| `ENABLE_OAUTH_ID_TOKEN_COOKIE` | `true` | For backward compatibility. Controls if the legacy `oauth_id_token` cookie is set. Recommended to set to `false`. |
### Server-Side OAuth Session Management
To solve issues related to large tokens (e.g., with AD FS group claims exceeding cookie size limits) and to enable automatic token refreshing, Open WebUI now supports a robust server-side session management system.
**How It Works:**
1. **Server-Side Storage:** Instead of storing large `access_token` and `id_token` values in browser cookies, the entire token payload is now encrypted and stored securely in the Open WebUI database in a new `oauth_session` table.
2. **Secure Session Cookie:** The user's browser is sent a single, small, and secure `httponly` cookie named `oauth_session_id`. This cookie acts as an opaque identifier, containing no sensitive information itself.
3. **Automatic Refresh:** When a token is required by a downstream service (like a tool or an OpenAI-compatible endpoint), the backend uses the `oauth_session_id` to retrieve the tokens. If the tokens are expired or close to expiring, the system automatically uses the stored `refresh_token` to fetch new ones from the provider before forwarding them. This ensures services always receive a valid token and prevents silent failures.
4. **Clean Token Access:** This architecture provides a clean and reliable way for internal tools and other services to access user tokens without fragile cookie-scraping.
This system is enabled by default but can be fine-tuned with the environment variables detailed above.
For more information, check out the [environment variable docs page](https://docs.openwebui.com/getting-started/env-configuration/).
### Google

View File

@@ -2832,6 +2832,26 @@ If the OAuth picture claim is disabled by setting `OAUTH_PICTURE_CLAIM` to `''`
:::
#### `ENABLE_OAUTH_ID_TOKEN_COOKIE`
- Type: `bool`
- Default: `True`
- Description: Controls whether the **legacy** `oauth_id_token` cookie (unsafe, not recommended, token can go stale/orphaned) is set in the browser upon a successful OAuth login. This is provided for **backward compatibility** with custom tools or older versions that might rely on scraping this cookie. **The new, recommended approach is to use the server-side session management.**
- Usage: For new and secure deployments, **it is recommended to set this to `False`** to minimize the information exposed to the client-side. Keep it as `True` only if you have integrations that depend on the old cookie-based method.
#### `OAUTH_SESSION_TOKEN_ENCRYPTION_KEY`
- Type: `str`
- Default: Falls back to the value of `WEBUI_SECRET_KEY`.
- Description: Specifies the secret key used to encrypt and decrypt OAuth tokens stored server-side in the database. This is a critical security component for protecting user credentials at rest. If not set, it defaults to using the main `WEBUI_SECRET_KEY`, but it is highly recommended to set it to a unique, securely generated value for production environments.
:::warning
**Required for Multi-Replica Deployments**
In any production environment running more than one instance of Open WebUI (e.g., Docker Swarm, Kubernetes), this variable **MUST** be explicitly set to a persistent, shared secret. If left unset, each replica will generate or use a different key, causing session decryption to fail intermittently as user requests are load-balanced across instances.
:::
#### `WEBUI_AUTH_TRUSTED_EMAIL_HEADER`
- Type: `str`