diff --git a/docs/docs/Configuration/configuration-api-keys.md b/docs/docs/Configuration/configuration-api-keys.md index 7569c7876..3a43dfae5 100644 --- a/docs/docs/Configuration/configuration-api-keys.md +++ b/docs/docs/Configuration/configuration-api-keys.md @@ -3,21 +3,18 @@ title: API keys slug: /configuration-api-keys --- -Langflow provides an API key functionality that allows users to access their individual components and flows without traditional login authentication. The API key is a user-specific token that can be included in the request header, query parameter, or as a command line argument to authenticate API calls. This documentation outlines how to generate, use, and manage API keys in Langflow. +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; -:::info +Langflow provides an API key functionality that allows users to access their individual components and flows without traditional login authentication. -The default user and password are set using the LANGFLOW_SUPERUSER and LANGFLOW_SUPERUSER_PASSWORD environment variables. The default values are `langflow` and `langflow`, respectively. - -::: - -## Generate an API key +## Generate a Langflow API key Generate a user-specific token to use with Langflow. ### Generate an API key with the Langflow UI -1. Click your user icon and select **Settings**. +1. Click your user icon, and then select **Settings**. 2. Click **Langflow API**, and then click **Add New**. 3. Name your key, and then click **Create Secret Key**. 4. Copy the API key and store it in a secure location. @@ -45,148 +42,74 @@ python -m langflow api-key Include your API key in API requests to authenticate requests to Langflow. +API keys allow access only to the flows and components of the specific user to whom the key was issued. + ### Include the API key in the HTTP header -To use the API key when making API requests with cURL, include the API key in the HTTP header. +To use the API key when making API requests, include the API key in the HTTP header: ```shell curl -X POST \ - "http://127.0.0.1:7860/api/v1/run/*`YOUR_FLOW_ID`*?stream=false" \ + "http://127.0.0.1:7860/api/v1/run/FLOW_ID?stream=false" \ -H 'Content-Type: application/json' \ - -H 'x-api-key: *`YOUR_API_KEY`*' \ + -H 'x-api-key: API_KEY' \ -d '{"inputs": {"text":""}, "tweaks": {}}' ``` -To instead pass the API key as a query parameter, do the following: +### Include the API key as a query parameter + +To pass the API key as a query parameter: ```shell curl -X POST \ - "http://127.0.0.1:7860/api/v1/run/*`YOUR_FLOW_ID`*?x-api-key=*`YOUR_API_KEY`*?stream=false" \ + "http://127.0.0.1:7860/api/v1/run/FLOW_ID?x-api-key=API_KEY?stream=false" \ -H 'Content-Type: application/json' \ -d '{"inputs": {"text":""}, "tweaks": {}}' ``` -To use the API key when making API requests with the Python `requests` library, include the API key as a variable string. +## Generate a Langflow secret key -```python -import argparse -import json -from argparse import RawTextHelpFormatter -import requests -from typing import Optional -import warnings -try: - from langflow.load import upload_file -except ImportError: - warnings.warn("Langflow provides a function to help you upload files to the flow. Please install langflow to use it.") - upload_file = None +Langflow uses the [Fernet](https://pypi.org/project/cryptography/) library for encrypting sensitive data. -BASE_API_URL = "http://127.0.0.1:7860" -FLOW_ID = "*`YOUR_FLOW_ID`*" -ENDPOINT = "" # You can set a specific endpoint name in the flow settings +If no `LANGFLOW_SECRET_KEY` is provided, Langflow automatically generates one. -# You can tweak the flow by adding a tweaks dictionary -# e.g {"OpenAI-XXXXX": {"model_name": "gpt-4"}} -TWEAKS = { - "ChatInput-8a86T": {}, - "Prompt-pKfl9": {}, - "ChatOutput-WcGpD": {}, - "OpenAIModel-5UyvQ": {} -} - -def run_flow(message: str, - endpoint: str, - output_type: str = "chat", - input_type: str = "chat", - tweaks: Optional[dict] = None, - api_key: Optional[str] = None) -> dict: - """ - Run a flow with a given message and optional tweaks. - - :param message: The message to send to the flow - :param endpoint: The ID or the endpoint name of the flow - :param tweaks: Optional tweaks to customize the flow - :return: The JSON response from the flow - """ - api_url = f"{BASE_API_URL}/api/v1/run/{endpoint}" - - payload = { - "input_value": message, - "output_type": output_type, - "input_type": input_type, - } - headers = None - if tweaks: - payload["tweaks"] = tweaks - if api_key: - headers = {"x-api-key": api_key} - response = requests.post(api_url, json=payload, headers=headers) - return response.json() - -def main(): - parser = argparse.ArgumentParser(description="""Run a flow with a given message and optional tweaks. -Run it like: python .py "your message here" --endpoint "your_endpoint" --tweaks '{"key": "value"}'""", - formatter_class=RawTextHelpFormatter) - parser.add_argument("message", type=str, help="The message to send to the flow") - parser.add_argument("--endpoint", type=str, default=ENDPOINT or FLOW_ID, help="The ID or the endpoint name of the flow") - parser.add_argument("--tweaks", type=str, help="JSON string representing the tweaks to customize the flow", default=json.dumps(TWEAKS)) - parser.add_argument("--api_key", type=str, help="API key for authentication", default=None) - parser.add_argument("--output_type", type=str, default="chat", help="The output type") - parser.add_argument("--input_type", type=str, default="chat", help="The input type") - parser.add_argument("--upload_file", type=str, help="Path to the file to upload", default=None) - parser.add_argument("--components", type=str, help="Components to upload the file to", default=None) - - args = parser.parse_args() - try: - tweaks = json.loads(args.tweaks) - except json.JSONDecodeError: - raise ValueError("Invalid tweaks JSON string") - - if args.upload_file: - if not upload_file: - raise ImportError("Langflow is not installed. Please install it to use the upload_file function.") - elif not args.components: - raise ValueError("You need to provide the components to upload the file to.") - tweaks = upload_file(file_path=args.upload_file, host=BASE_API_URL, flow_id=args.endpoint, components=[args.components], tweaks=tweaks) - - response = run_flow( - message=args.message, - endpoint=args.endpoint, - output_type=args.output_type, - input_type=args.input_type, - tweaks=tweaks, - api_key=args.api_key - ) - - print(json.dumps(response, indent=2)) - -if __name__ == "__main__": - main() - -``` - -To pass the API key to your script with a command line argument, do the following: - -```shell -python your_script.py "*`YOUR_INPUT_MESSAGE`*" --api_key "*`YOUR_API_KEY`*" -``` - -## Security considerations - -- **Visibility**: For security reasons, the API key cannot be retrieved again through the UI. -- **Scope**: The key allows access only to the flows and components of the specific user to whom it was issued. - -## Custom API endpoint - -To choose a custom name for your API endpoint, select **Project Settings** > **Endpoint Name** and name your endpoint. +For more information, see [Authentication](/configuration-authentication#langflow_secret_key). ## Revoke an API key To revoke an API key, delete it from the list of keys in the **Settings** menu. -1. Click your user icon and select **Settings**. +1. Click your user icon, and then select **Settings**. 2. Click **Langflow API**. 3. Select the keys you want to delete and click the trash can icon. This action immediately invalidates the key and prevents it from being used again. +## Add component API keys to Langflow + +These are credentials for external services like OpenAI. They can be added to Langflow with the `.env` file or in the Langflow UI. + +Component API keys that are set in the UI override those that are set in the environment variables. + +### Add component API keys with the .env file + +To add component API keys to your `.env` file: + +```text +OPENAI_API_KEY=sk-... +ANTHROPIC_API_KEY=sk-... +GOOGLE_API_KEY=... +``` + +### Add component API keys with the Langflow UI + +To add component API keys as **Global variables** with the Langflow UI: + +1. Click your user icon, and then select **Settings**. +2. Click **Langflow API**. +3. Add new API keys as **Credential** type variables. +4. Apply them to specific component fields. + +Component values set directly in a flow override values set in the UI **and** environment variables. + +For more information, see [Global variables](/configuration-global-variables). \ No newline at end of file diff --git a/docs/docs/Configuration/configuration-authentication.md b/docs/docs/Configuration/configuration-authentication.md index 6c494b1cd..ae15476af 100644 --- a/docs/docs/Configuration/configuration-authentication.md +++ b/docs/docs/Configuration/configuration-authentication.md @@ -6,119 +6,53 @@ slug: /configuration-authentication import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; -The login functionality in Langflow serves to authenticate users and protect sensitive routes in the application. - -## Create a superuser and new users in Langflow - -Learn how to create a new superuser, log in to Langflow, and add new users. - -1. Create a `.env` file and open it in your preferred editor. - -2. Add the following environment variables to your file. - -```bash -LANGFLOW_AUTO_LOGIN=False -LANGFLOW_SUPERUSER=admin -LANGFLOW_SUPERUSER_PASSWORD=securepassword -LANGFLOW_SECRET_KEY=randomly_generated_secure_key -LANGFLOW_NEW_USER_IS_ACTIVE=False -``` - -For more information, see [Authentication configuration values](#values). +This guide covers Langflow's authentication system and API key management, including how to secure your deployment and manage access to flows and components. :::tip The Langflow project includes a [`.env.example`](https://github.com/langflow-ai/langflow/blob/main/.env.example) file to help you get started. You can copy the contents of this file into your own `.env` file and replace the example values with your own preferred settings. ::: -3. Save your `.env` file. -4. Run Langflow with the configured environment variables. +## Authentication configuration values -```bash -python -m langflow run --env-file .env -``` - -5. Sign in with your username `admin` and password `securepassword`. -6. To open the **Admin Page**, click your user profile image, and then select **Admin Page**. - You can also go to `http://127.0.0.1:7861/admin`. -7. To add a new user, click **New User**, and then add the **Username** and **Password**. -8. To activate the new user, select **Active**. - The user can only sign in if you select them as **Active**. -9. To give the user `superuser` privileges, click **Superuser**. -10. Click **Save**. -11. To confirm your new user has been created, sign out of Langflow, and then sign back in using your new **Username** and **Password**. - -## Manage Superuser with the Langflow CLI - -Langflow provides a command-line utility for interactively creating superusers: - -1. Enter the CLI command: - -```bash -langflow superuser -``` - -2. Langflow prompts you for a **Username** and **Password**: - -``` -langflow superuser -Username: new_superuser_1 -Password: -Default folder created successfully. -Superuser created successfully. -``` - -3. To confirm your new superuser was created successfully, go to the **Admin Page** at `http://127.0.0.1:7861/admin`. - -## Authentication configuration values {#values} - -The following table lists the available authentication configuration variables, their descriptions, and default values: - -| Variable | Description | Default | -| ----------------------------- | ------------------------------------- | ------- | -| `LANGFLOW_AUTO_LOGIN` | Enables automatic login | `True` | -| `LANGFLOW_SUPERUSER` | Superuser username | - | -| `LANGFLOW_SUPERUSER_PASSWORD` | Superuser password | - | -| `LANGFLOW_SECRET_KEY` | Key for encrypting superuser password | - | -| `LANGFLOW_NEW_USER_IS_ACTIVE` | Automatically activates new users | `False` | +The section describes the available authentication configuration variables. ### LANGFLOW_AUTO_LOGIN -By default, this variable is set to `True`. When enabled, Langflow operates as it did in versions prior to 0.5, including automatic login without requiring explicit user authentication. +When `True`, Langflow automatically logs users in with username `langflow` and password `langflow` without requiring user authentication. +To disable automatic login and enforce user authentication, set this value to `False` in your `.env` file. +By default, this variable is set to `True`. -To disable automatic login and enforce user authentication: - -```shell -LANGFLOW_AUTO_LOGIN=False +```bash +LANGFLOW_AUTO_LOGIN=True ``` ### LANGFLOW_SUPERUSER and LANGFLOW_SUPERUSER_PASSWORD -These environment variables are only relevant when LANGFLOW_AUTO_LOGIN is set to False. They specify the username and password for the superuser, which is essential for administrative tasks. -To create a superuser manually: +These environment variables are only relevant when `LANGFLOW_AUTO_LOGIN` is set to `False`. +They specify the username and password for the superuser, which is essential for administrative tasks: -```bash -LANGFLOW_SUPERUSER=admin +```text +LANGFLOW_SUPERUSER=administrator LANGFLOW_SUPERUSER_PASSWORD=securepassword ``` ### LANGFLOW_SECRET_KEY This environment variable holds a secret key used for encrypting sensitive data like API keys. +Langflow uses the [Fernet](https://pypi.org/project/cryptography/) library for secret key encryption. -```bash +```text LANGFLOW_SECRET_KEY=dBuuuB_FHLvU8T9eUNlxQF9ppqRxwWpXXQ42kM2_fb ``` -Langflow uses the [Fernet](https://pypi.org/project/cryptography/) library for secret key encryption. +:::warning +If no secret key is provided, Langflow automatically generates one. This is not recommended for production environments, especially in multi-instance deployments like Kubernetes, where auto-generated keys can't decrypt data encrypted by other instances. +::: -### Create a LANGFLOW_SECRET_KEY +To generate a `LANGFLOW_SECRET_KEY`, follow these steps: -The `LANGFLOW_SECRET_KEY` is used for encrypting sensitive data. It must be: -- At least 32 bytes long -- URL-safe base64 encoded - -1. To create a `LANGFLOW_SECRET_KEY`, run the following command: +1. Run the command to generate and copy a secret to the clipboard. @@ -148,43 +82,108 @@ python -c "from secrets import token_urlsafe; print(f'LANGFLOW_SECRET_KEY={token -The command generates a secure key like `dBuuuB_FHLvU8T9eUNlxQF9ppqRxwWpXXQ42kM2_fbg`. -Treat the generated secure key as you would an application access token. Do not commit the key to code and keep it in a safe place. - -2. Create a `.env` file with the following configuration, and include your generated secret key value. -```bash -LANGFLOW_AUTO_LOGIN=False -LANGFLOW_SUPERUSER=admin -LANGFLOW_SUPERUSER_PASSWORD=securepassword -LANGFLOW_SECRET_KEY=dBuuuB_FHLvU8T9eUNlxQF9ppqRxwWpXXQ42kM2_fbg # Your generated key -LANGFLOW_NEW_USER_IS_ACTIVE=False -``` - -3. Start Langflow with the values from your `.env` file. -```bash -uv run langflow run --env-file .env -``` - -The generated secret key value is now used to encrypt your global variables. - -If no key is provided, Langflow will automatically generate a secure key. This is not recommended for production environments, because in a multi-instance deployment like Kubernetes, auto-generated keys won't be able to decrypt data encrypted by other instances. Instead, you should explicitly set the `LANGFLOW_SECRET_KEY` environment variable in the deployment configuration to be the same across all instances. - -### Rotate the LANGFLOW_SECRET_KEY - -To rotate the key, follow these steps. - -1. Create a new `LANGFLOW_SECRET_KEY` with the command in [Create a LANGFLOW_SECRET_KEY](#create-a-langflow_secret_key). -2. Stop your Langflow instance. -3. Update the `LANGFLOW_SECRET_KEY` in your `.env` file with the new key. -4. Restart Langflow with the updated environment file: -```bash -langflow run --env-file .env +2. Paste the value into your `.env` file: +```text +LANGFLOW_SECRET_KEY=dBuuuB_FHLvU8T9eUNlxQF9ppqRxwWpXXQ42kM2_fb ``` ### LANGFLOW_NEW_USER_IS_ACTIVE -By default, this variable is set to `False`. When enabled, new users are automatically activated and can log in without requiring explicit activation by the superuser. +When this option is set to `True`, new users are automatically activated and can log in without requiring explicit activation by the superuser from the **Admin page**. +By default, this variable is set to `False`. + +```text +LANGFLOW_NEW_USER_IS_ACTIVE=False +``` + +## Start a secure Langflow server with authentication + +Start a secure Langflow server with authentication enabled and secret key encryption using the variables described in [Authentication configuration values](/configuration-authentication#authentication-configuration-values). + +Once you are logged in as a superuser, create a new user on your server. + +### Start the Langflow server + +1. Create a `.env` file and populate it with values for a secure server. +This server creates a superuser account, requires users to log in before using Langflow, and encrypts secrets with `LANGFLOW_SECRET_KEY`, which is added in the next step. +Create a `.env` file with the following configuration: + +```text +LANGFLOW_AUTO_LOGIN=False +LANGFLOW_SUPERUSER=administrator +LANGFLOW_SUPERUSER_PASSWORD=securepassword +LANGFLOW_SECRET_KEY=your_generated_key +LANGFLOW_NEW_USER_IS_ACTIVE=False +``` + +2. Generate a secret key for encrypting sensitive data. + +Generate your secret key using one of the following commands: + + + ```bash -LANGFLOW_NEW_USER_IS_ACTIVE=False -``` \ No newline at end of file +# Copy to clipboard (macOS) +python3 -c "from secrets import token_urlsafe; print(f'LANGFLOW_SECRET_KEY={token_urlsafe(32)}')" | pbcopy + +# Copy to clipboard (Linux) +python3 -c "from secrets import token_urlsafe; print(f'LANGFLOW_SECRET_KEY={token_urlsafe(32)}')" | xclip -selection clipboard + +# Or just print +python3 -c "from secrets import token_urlsafe; print(f'LANGFLOW_SECRET_KEY={token_urlsafe(32)}')" +``` + + + + +```bash +# Copy to clipboard +python -c "from secrets import token_urlsafe; print(f'LANGFLOW_SECRET_KEY={token_urlsafe(32)}')" | clip + +# Or just print +python -c "from secrets import token_urlsafe; print(f'LANGFLOW_SECRET_KEY={token_urlsafe(32)}')" +``` + + + + +3. Paste your `LANGFLOW_SECRET_KEY` into the `.env` file. + +4. Start Langflow with the configuration from your `.env` file. + +```text +uv run langflow run --env-file .env +``` + +5. Verify the server is running. The default location is `http://localhost:7860`. + +### Manage users as an administrator + +1. To complete your first-time login as a superuser, go to `http://localhost:7860/login`. +2. Log in with your superuser credentials: +* Username: Value of `LANGFLOW_SUPERUSER` (for example, `administrator`) +* Password: Value of `LANGFLOW_SUPERUSER_PASSWORD` (for example, `securepassword`) + +:::info +The default values are `langflow` and `langflow`. +::: + +3. To manage users on your server, navigate to the `/admin` page at `http://localhost:7860/admin`. +Click your user profile image, and then click **Admin Page**. + +As a superuser, you can create users, set permissions, reset passwords, and delete accounts. + +4. To create a user, in the Langflow UI, click **New User**, and then complete the following fields: +* **Username** +* **Password** and **Confirm Password** +* Select **Active** and deselect **Superuser** for the new user. +**Active** users can log into the system and access their flows. **Inactive** users cannot log in or see their flows. +A **Superuser** has full administrative privileges. + +5. To complete user creation, click **Save**. +Your new user appears in the **Admin Page**. +6. To confirm your new user's functionality, log out of Langflow, and log back in with your new user's credentials. +Attempt to access the `/admin` page. You should be redirected to the `/flows` page, because the new user is not a superuser. + +You have started a secure Langflow server with authentication enabled and secret key encryption. \ No newline at end of file