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

# Add Login to Your Flask Application

> Add Auth0 authentication to a Flask web application with login, protected routes, and user profiles

> [!NOTE]
>
> **Prerequisites:** Before you begin, ensure you have the following installed:
>
> * **[Python](https://www.python.org/downloads/)** 3.9 or newer
> * **[pip](https://pip.pypa.io/en/stable/installation/)** 20.0 or newer
> * **[jq](https://jqlang.org/)** - Required for Auth0 CLI setup
>
> **Flask Version Compatibility:** This quickstart uses **Flask 2.0+** with the `[async]` extra for async support.

## Get Started

This quickstart demonstrates how to add Auth0 authentication to a Flask application. You'll build a secure web application with login functionality, protected routes, and user profile access using the [Auth0 WebApp Python SDK](https://github.com/auth0/auth0-server-python).

**1. Set up your environment**

Create a new directory for your Flask project:

```bash theme={null}
mkdir auth0-flask-app && cd auth0-flask-app
```

Create a virtual environment:

```bash theme={null}
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

**2. Install dependencies**

Create `requirements.txt` to track your dependencies:

```txt requirements.txt theme={null}
auth0-server-python>=1.0.0b7
flask[async]>=2.0.0
python-dotenv>=1.0.0
```

The `requirements.txt` file tracks all project dependencies. To install them, run:

```bash theme={null}
pip install -r requirements.txt
```

**3. Setup your Auth0 App**

Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project.

You can choose to set up your Auth0 app automatically by running a CLI command, or do it manually via the Dashboard:

> [tab] CLI
>
> Run the following shell command on your project's root directory to create an Auth0 application and generate a `.env` file:
>
> ```shellscript Mac theme={null}
> # Install Auth0 CLI (if not already installed)
> brew tap auth0/auth0-cli && brew install auth0
>
> # Set up Auth0 app and generate .env file
> auth0 qs setup --app --type regular --framework vanilla-python --port 5000 --name "My Flask App"
> ```
>
> ```powershell Windows theme={null}
> # Install Auth0 CLI (if not already installed)
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Set up Auth0 app and generate .env file
> auth0 qs setup --app --type regular --framework vanilla-python --port 5000 --name "My Flask App"
> ```
>
> > [!NOTE]
> >
> > This command will:
> >
> > 1. Check if you're authenticated (and prompt for login if needed)
> > 2. Create an Auth0 Regular Web Application configured for `http://localhost:5000`
> > 3. Generate a `.env` file with `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, `AUTH0_CLIENT_SECRET`, `AUTH0_SECRET`, and `AUTH0_REDIRECT_URI`

> [tab] Dashboard
>
> Before you start, create a `.env` file in your project root:
>
> ```bash .env theme={null}
> # Auth0 Configuration
> AUTH0_DOMAIN=YOUR_AUTH0_DOMAIN
> AUTH0_CLIENT_ID=YOUR_CLIENT_ID
> AUTH0_CLIENT_SECRET=YOUR_CLIENT_SECRET
> AUTH0_SECRET=YOUR_GENERATED_SECRET
> AUTH0_REDIRECT_URI=http://localhost:5000/callback
> ```
>
> 1. Go to [Auth0 Dashboard](https://manage.auth0.com/dashboard/) → **Applications** → **Applications**
> 2. Click **Create Application**
> 3. Name your application (e.g., "My Flask App") and select **Regular Web Application**
> 4. Click **Create**
> 5. In the **Settings** tab, configure the following:
>    * **Allowed Callback URLs**: `http://localhost:5000/callback`
>    * **Allowed Logout URLs**: `http://localhost:5000`
>    * **Allowed Web Origins**: `http://localhost:5000`
> 6. Click **Save Changes**
> 7. Replace `YOUR_AUTH0_DOMAIN` in `.env` with your **Domain** from the Settings tab (e.g., `your-tenant.auth0.com`)
> 8. Replace `YOUR_CLIENT_ID` in `.env` with your **Client ID**
> 9. Replace `YOUR_CLIENT_SECRET` in `.env` with your **Client Secret**
>
> Generate a secure secret for `AUTH0_SECRET`:
>
> ```bash theme={null}
> openssl rand -hex 64
> ```
>
> > [!NOTE]
> >
> > **Important:** Never commit your `.env` file to version control. Add it to `.gitignore`.

**4. Create Auth Configuration, Routes, and Templates**

Create files

```bash theme={null}
mkdir templates static && touch app.py auth.py templates/index.html templates/profile.html static/style.css
```

And add the following code snippets:

> [!NOTE]
>
> **Development Only:** This example uses simple in-memory storage classes (`MemoryStateStore` and `MemoryTransactionStore`) for demonstration purposes. These stores will lose all session data when your application restarts and won't work in multi-instance deployments.
>
> **For production applications**, you must implement persistent storage. The SDK is framework-agnostic and requires you to provide custom `StateStore` and `TransactionStore` implementations. See the [official SDK storage examples](https://github.com/auth0/auth0-server-python/blob/main/examples/ConfigureStore.md) for detailed guidance on implementing Redis, PostgreSQL, or other persistent storage backends.

**5. Run your app**

Start the Flask development server:

```bash theme={null}
python app.py
```

Your app will be available at [http://localhost:5000](http://localhost:5000). The Auth0 SDK handles authentication routes automatically.

> [!TIP]
>
> **Checkpoint**
>
> You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:5000/)

***

## Advanced Usage

> [accordion] Accessing API Tokens
>
> If you need to call a protected API, retrieve an access token:
>
> ```python theme={null}
> @app.route('/api-call')
> @require_auth
> async def api_call():
>     try:
>         # Get access token for your API
>         access_token = await auth0.get_access_token(
>             audience='https://your-api.example.com',
>             store_options=g.store_options
>         )
>
>         # Use the token to call your API
>         # headers = {'Authorization': f'Bearer {access_token}'}
>         # response = requests.get('https://your-api.example.com/data', headers=headers)
>
>         return f"Access token retrieved: {access_token[:20]}..."
>     except Exception as e:
>         return f"Error getting access token: {str(e)}", 500
> ```
>
> > [!NOTE]
> >
> > To use this feature, you must:
> >
> > 1. Set `AUTH0_AUDIENCE` in your `.env` file
> > 2. Include `offline_access` in your scopes (for refresh tokens)
> > 3. Update `authorization_params` in `auth.py`:
> >    ```python theme={null}
> >    authorization_params={
> >        'scope': 'openid profile email offline_access',
> >        'audience': os.getenv('AUTH0_AUDIENCE')
> >    }
> >    ```

> [accordion] Custom Storage Configuration
>
> By default, the SDK uses cookie-based storage. For production environments with specific needs (horizontal scaling, session sharing across services), you can configure custom storage backends like Redis or PostgreSQL.
>
> **When to use custom storage:**
>
> * You need to share sessions across multiple servers
> * You have large session data exceeding cookie size limits
> * You need centralized session management for backchannel logout
>
> **Redis Example:**
>
> ```python auth.py theme={null}
> from auth0_server_python.stores.redis_state_store import RedisStateStore
> import redis.asyncio as redis
>
> # Initialize custom state store
> redis_client = redis.from_url(os.getenv('REDIS_URL', 'redis://localhost:6379'))
> state_store = RedisStateStore(
>     secret=os.getenv('AUTH0_SECRET'),
>     redis_client=redis_client
> )
>
> # Pass to ServerClient
> auth0 = ServerClient(
>     domain=os.getenv('AUTH0_DOMAIN'),
>     client_id=os.getenv('AUTH0_CLIENT_ID'),
>     client_secret=os.getenv('AUTH0_CLIENT_SECRET'),
>     secret=os.getenv('AUTH0_SECRET'),
>     redirect_uri=os.getenv('AUTH0_REDIRECT_URI'),
>     state_store=state_store,  # Custom storage
>     authorization_params={'scope': 'openid profile email'}
> )
> ```
>
> > [!NOTE]
> >
> > For most applications, the default cookie-based storage is sufficient. Custom storage requires implementing the `StateStore` interface. See the [SDK examples](https://github.com/auth0/auth0-server-python/blob/main/examples/ConfigureStore.md) for detailed implementations.

***

## Common Issues

> [accordion] MissingRequiredArgumentError
>
> **Problem:** You see "MissingRequiredArgumentError: secret" when starting the app
>
> **Cause:** The `AUTH0_SECRET` environment variable is missing or not loaded properly.
>
> **Solution:**
>
> 1. Verify your `.env` file exists in the project root
> 2. Ensure `python-dotenv` is installed: `pip install python-dotenv`
> 3. Generate a new secret if needed: `openssl rand -hex 64`
> 4. Add it to `.env`: `AUTH0_SECRET=your_generated_secret`
> 5. Restart your Flask application

> [accordion] Invalid Callback URL Error
>
> **Problem:** You see "Callback URL mismatch" or "invalid\_request" error during login
>
> **Cause:** The redirect URI in your code doesn't match what's registered in Auth0 Dashboard.
>
> **Solution:**
>
> 1. Check your `.env` file: `AUTH0_REDIRECT_URI=http://localhost:5000/callback`
> 2. Go to [Auth0 Dashboard](https://manage.auth0.com/dashboard/) → Applications → Your App → Settings
> 3. Add `http://localhost:5000/callback` to **Allowed Callback URLs**
> 4. Click **Save Changes**
> 5. Restart your Flask application

> [accordion] AsyncIO Event Loop Errors
>
> **Problem:** You see "RuntimeError: This event loop is already running" or similar async errors
>
> **Cause:** Flask 2.0+ async support may have issues with certain configurations.
>
> **Solution:**
>
> Install Flask with async support:
>
> ```bash theme={null}
> pip install "flask[async]"
> ```
>
> Then restart your Flask application.

> [accordion] Module Not Found Errors
>
> **Problem:** You see "ModuleNotFoundError: No module named 'auth0\_server\_python'" or similar
>
> **Cause:** The SDK is not installed or the virtual environment is not activated.
>
> **Solution:**
>
> 1. Ensure your virtual environment is activated:
>    ```bash theme={null}
>    source venv/bin/activate  # macOS/Linux
>    # or
>    venv\Scripts\activate  # Windows
>    ```
> 2. Install the SDK:
>    ```bash theme={null}
>    pip install auth0-server-python "flask[async]" python-dotenv
>    ```
> 3. Verify installation:
>
> ```bash theme={null}
> pip list | grep auth0
> ```

> [accordion] ClaimDecodingFailed Error
>
> **Problem:** You see "ClaimDecodingFailed" or "Failed to decode claims" error during authentication
>
> **Cause:** The ID token or access token received from Auth0 couldn't be properly decoded, often due to:
>
> * Invalid JWT format
> * Corrupted session data
> * Mismatched signing algorithms
> * Clock skew between your server and Auth0
>
> **Solution:**
>
> 1. Ensure your `AUTH0_CLIENT_SECRET` is correct in the `.env` file
> 2. Check your system time is synchronized (NTP):
>    ```bash theme={null}
>    # macOS
>    sudo sntp -sS time.apple.com
>
>    # Linux
>    sudo ntpdate -s time.nist.gov
>    ```
> 3. Clear browser cookies and restart authentication
> 4. Verify the `AUTH0_DOMAIN` doesn't include `https://` prefix
> 5. Check Auth0 Dashboard → Applications → Your App → Settings → Advanced → OAuth → JsonWebToken Signature Algorithm matches your SDK configuration

> [accordion] Token Expired or Invalid
>
> **Problem:** You see "Token has expired" or "invalid\_token" errors
>
> **Cause:** The access token or ID token has exceeded its lifetime, or the session has expired.
>
> **Solution:**
>
> 1. The SDK automatically handles token refresh if you include `offline_access` scope:
>    ```python theme={null}
>    authorization_params={
>        'scope': 'openid profile email offline_access',
>    }
>    ```
> 2. For APIs, ensure you're requesting fresh tokens:
>    ```python theme={null}
>    access_token = await auth0.get_access_token(
>        audience='https://your-api.example.com',
>        force_refresh=True  # Force refresh if needed
>    )
>    ```
> 3. Adjust token lifetimes in Auth0 Dashboard → Applications → Your App → Settings → Advanced → OAuth
> 4. Implement proper error handling to redirect users to login when tokens expire

> [accordion] CORS and Cross-Origin Errors
>
> **Problem:** You see CORS errors or "Blocked by CORS policy" in browser console
>
> **Cause:** Your application's origin isn't properly configured in Auth0.
>
> **Solution:**
>
> 1. Add your origin to Auth0 Dashboard → Applications → Your App → Settings:
>    * **Allowed Web Origins**: `http://localhost:5000`
>    * **Allowed Callback URLs**: `http://localhost:5000/callback`
>    * **Allowed Logout URLs**: `http://localhost:5000`
> 2. For production, add your production URLs:
>    ```
>    https://yourdomain.com
>    https://yourdomain.com/callback
>    ```
> 3. Ensure your Flask app has proper CORS configuration if calling Auth0 APIs from frontend JavaScript:
>    ```python theme={null}
>    from flask_cors import CORS
>    CORS(app, origins=['http://localhost:5000'])
>    ```

> [accordion] Rate Limit Exceeded
>
> **Problem:** You see "Too many requests" or "Rate limit exceeded" errors
>
> **Cause:** Your application has exceeded Auth0's rate limits for authentication requests.
>
> **Solution:**
>
> 1. Check Auth0 Dashboard → Monitoring → Logs for rate limit details
> 2. Implement exponential backoff for retries:
>    ```python theme={null}
>    import time
>    from auth0_server_python.error import ApiError
>
>    async def login_with_retry():
>        max_retries = 3
>        for attempt in range(max_retries):
>            try:
>                return await auth0.start_interactive_login({}, g.store_options)
>            except ApiError as e:
>                if e.status_code == 429 and attempt < max_retries - 1:
>                    wait_time = 2 ** attempt
>                    time.sleep(wait_time)
>                else:
>                    raise
>    ```
> 3. Review your Auth0 subscription plan limits
> 4. Optimize authentication flow to reduce unnecessary token requests
> 5. Cache tokens appropriately instead of requesting new ones frequently
