From 44a97b6fe8c828300f954d34b5526606314895ee Mon Sep 17 00:00:00 2001 From: sanchitmehta94 Date: Thu, 22 Jan 2026 11:25:31 +0530 Subject: [PATCH 1/2] revamp conten of Python server quickstart --- main/docs.json | 6 +- main/docs/quickstart/webapp/python/_index.mdx | 182 --- main/docs/quickstart/webapp/python/index.mdx | 1083 ++++++++++++----- .../quickstart/webapp/python/interactive.mdx | 202 --- 4 files changed, 800 insertions(+), 673 deletions(-) delete mode 100644 main/docs/quickstart/webapp/python/_index.mdx delete mode 100644 main/docs/quickstart/webapp/python/interactive.mdx diff --git a/main/docs.json b/main/docs.json index a30ee8e16f..ed8c70ebfb 100644 --- a/main/docs.json +++ b/main/docs.json @@ -2390,7 +2390,7 @@ "docs/quickstart/webapp/nextjs/index", "docs/quickstart/webapp/nuxt/index", "docs/quickstart/webapp/express/interactive", - "docs/quickstart/webapp/python/interactive", + "docs/quickstart/webapp/python/index", "docs/quickstart/webapp/django/interactive", "docs/quickstart/webapp/golang/interactive", "docs/quickstart/webapp/java/interactive", @@ -5025,7 +5025,7 @@ "pages": [ "docs/fr-ca/quickstart/webapp/nextjs/interactive", "docs/fr-ca/quickstart/webapp/express/interactive", - "docs/fr-ca/quickstart/webapp/python/interactive", + "docs/fr-ca/quickstart/webapp/python/index", "docs/fr-ca/quickstart/webapp/django/interactive", "docs/fr-ca/quickstart/webapp/golang/interactive", "docs/fr-ca/quickstart/webapp/java/interactive", @@ -7372,7 +7372,7 @@ "pages": [ "docs/ja-jp/quickstart/webapp/nextjs/interactive", "docs/ja-jp/quickstart/webapp/express/interactive", - "docs/ja-jp/quickstart/webapp/python/interactive", + "docs/ja-jp/quickstart/webapp/python/index", "docs/ja-jp/quickstart/webapp/django/interactive", "docs/ja-jp/quickstart/webapp/golang/interactive", "docs/ja-jp/quickstart/webapp/java/interactive", diff --git a/main/docs/quickstart/webapp/python/_index.mdx b/main/docs/quickstart/webapp/python/_index.mdx deleted file mode 100644 index 29ef439790..0000000000 --- a/main/docs/quickstart/webapp/python/_index.mdx +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Add Login to Your Python Flask Application -sidebarTitle: Python - ---- -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Server from "/snippets/quickstart/webapp/python/server.py.mdx"; -import Home from "/snippets/quickstart/webapp/python/home.html.mdx"; - -import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; - -export const sections = [ - { id: "configure-auth0", title: "Configure Auth0" }, - { id: "install-dependencies", title: "Install dependencies" }, - { id: "configure-your-env-file", title: "Configure your .env file" }, - { id: "setup-your-application", title: "Setup your application" }, - { id: "setup-your-routes", title: "Setup your routes" }, - { id: "add-templates", title: "Add templates" }, - { id: "run-your-application", title: "Run your application" } -] - - - - Auth0 allows you to add authentication and gain access to user profile information in your application. This guide - demonstrates how to integrate Auth0 with a Python [Flask](https://flask.palletsprojects.com/) application using the [Authlib](https://authlib.org/) SDK. - -
- To use Auth0 services, you’ll need to have an application set up in the Auth0 Dashboard. The Auth0 application is - where you will configure how you want authentication to work for the project you are developing. - - ### Configure an application - - Use the interactive selector to create a new Auth0 application or select an existing application that represents - the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID - that your application code will use to call Auth0 APIs through the SDK. - - Any settings you configure using this quickstart will automatically update for your Application in the [Dashboard](https://manage.auth0.com/#/), which is where you - can manage your Applications in the future. - - If you would rather explore a complete configuration, you can view a sample application instead. - - ### Configure Callback URLs - - A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have - authenticated. If not set, users will not be returned to your application after they log in. - - - If you are following along with our sample project, set this to - `http://localhost:3000/callback`. - - - ### Configure Logout URLs - - A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged - out. If not set, users will not be able to log out from your application and will receive an error. - - - If you are following along with our sample project, set this to `http://localhost:3000`. - - - -
- -
- Create a `requirements.txt` file in your project directory: - - ```txt lines - # 📁 requirements.txt ----- - flask>=2.0.3 - python-dotenv>=0.19.2 - authlib>=1.0 - requests>=2.27.1 - ``` - - - Run the following command from your shell to enable these dependencies in your project: - - ```bash lines - pip install -r requirements.txt - ``` - - - -
- -
- Next, create an `.env` file in your project directory. This file will hold your client keys and other - configuration details. - - ```env lines - # 📁 .env ----- - AUTH0_CLIENT_ID={yourClientId} - AUTH0_CLIENT_SECRET={yourClientSecret} - AUTH0_DOMAIN={yourDomain} - APP_SECRET_KEY= - ``` - - - - Generate a string for `APP_SECRET_KEY`using `openssl rand -hex 32`from your shell. - - -
- -
- Next, set up your application. Create a `server.py` file in your project directory - this file will - contain your application logic. - - Import all the libraries your application needs. - - Load the configuration `.env` file you made in the previous step. - - Configure Authlib to handle your application's authentication with Auth0. To learn more about the configuration - options available for Authlib's OAuth `register()` method from [their documentation.](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) - - - - - -
- -
- In this example, you will add four routes to the application: login, callback, logout, and home. - - When visitors to your app visit the `/login` route, your application will route them to the Auth0 - login page. - - After your users log in with Auth0, your application will route them to the `/callback` route. This - route saves the session for the user and bypasses the need for them to login again when they return. - - The `/logout` route signs users out from your application. This route clears the user session in your - app and redirects to the Auth0 logout endpoint to ensure the session is no longer saved. Then, the application - redirects the user to your home route. - - Your `/`home route either renders an authenticated user's details or allows visitors to sign in. - - - - - -
- -
- Next, create the template file used in the home route (during `render_template()` calls). - - Create a new sub-directory in your project folder named `templates`, and create `home.html` - in the directory. Paste the content from the right into that file. - - -
- -
- To run your application, navigate to the root of your project directory and open a terminal. Run the following - command: - - ```bash lines - python3 server.py - ``` - - - ##### Checkpoint - - Visit [http://localhost:3000](http://localhost:3000/) to verify. You should find a login button routing to - Auth0 for login, then back to your application to see your profile information. - - - -
- - ## Next Steps - - Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application. - - This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out: - - * [Auth0 Dashboard](https://manage.auth0.com/dashboard/us/dev-gja8kxz4ndtex3rq) - Learn how to configure and manage your Auth0 tenant and applications - * [auth0-python SDK](https://github.com/auth0/auth0-python) - Explore the SDK used in this tutorial more fully - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Discover integrations you can enable to extend Auth0’s functionality -
- - -
diff --git a/main/docs/quickstart/webapp/python/index.mdx b/main/docs/quickstart/webapp/python/index.mdx index 96f94b21b7..78773447fc 100644 --- a/main/docs/quickstart/webapp/python/index.mdx +++ b/main/docs/quickstart/webapp/python/index.mdx @@ -1,334 +1,845 @@ --- -title: "Python" +title: 'Add Login to Your Flask Application' +description: 'Add Auth0 authentication to a Flask web application with login, protected routes, and user profiles' --- -import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; + + **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 + - **[OpenSSL](https://www.openssl.org/)** - For generating secure secrets + + **Flask Version Compatibility:** This quickstart uses **Flask 2.0+** which supports async routes with `async def`. For better async support, you can also use **[Quart](https://quart.palletsprojects.com/)**, an async-compatible Flask alternative. + + +## 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 server-side Python SDK. + + + + Create a new directory for your Flask project: + + ```bash + mkdir auth0-flask-app && cd auth0-flask-app + ``` + + Create a virtual environment: + + ```bash + python -m venv venv + source venv/bin/activate # On Windows: venv\Scripts\activate + ``` + + + A virtual environment isolates your project dependencies and prevents conflicts with system-wide Python packages. + + + + Install the SDK and Flask: + + ```bash + pip install auth0-server-python flask python-dotenv + ``` + + + `python-dotenv` is used to load environment variables from a `.env` file for secure configuration management. + + + + Create the necessary directories and files for your Flask application: + + ```bash + mkdir templates static && touch app.py auth.py .env templates/index.html templates/profile.html + ``` + + + You can choose to set up your Auth0 application automatically using the CLI or manually via the Dashboard: + + + + Run the following shell command on your project's root directory to create an Auth0 application and update your `.env` file: + + + + ```bash + AUTH0_APP_NAME="My Flask App" && \ + brew tap auth0/auth0-cli && brew install auth0 && \ + auth0 login --no-input && \ + auth0 apps create \ + -n "${AUTH0_APP_NAME}" \ + -t regular \ + -c http://localhost:5000/callback \ + -l http://localhost:5000 \ + -o http://localhost:5000 \ + --reveal-secrets \ + --json \ + --metadata created_by="quickstart-docs-manual" > app-details.json && \ + CLIENT_ID=$(python3 -c "import json; print(json.load(open('app-details.json'))['client_id'])") && \ + CLIENT_SECRET=$(python3 -c "import json; print(json.load(open('app-details.json'))['client_secret'])") && \ + DOMAIN=$(auth0 tenants list --json | python3 -c "import sys, json; print([t['name'] for t in json.load(sys.stdin) if t.get('active')][0])") && \ + SECRET=$(openssl rand -hex 64) && \ + echo "AUTH0_DOMAIN=${DOMAIN}" > .env && \ + echo "AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env && \ + echo "AUTH0_CLIENT_SECRET=${CLIENT_SECRET}" >> .env && \ + echo "AUTH0_SECRET=${SECRET}" >> .env && \ + echo "AUTH0_REDIRECT_URI=http://localhost:5000/callback" >> .env && \ + rm app-details.json && \ + echo "✅ Auth0 app created and .env file generated successfully!" + ``` + + + + ```powershell + $AppName = "My Flask App"; ` + winget install Auth0.CLI; ` + auth0 login --no-input; ` + auth0 apps create -n "$AppName" -t regular -c http://localhost:5000/callback -l http://localhost:5000 -o http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-manual" | Set-Content -Path app-details.json; ` + $Details = Get-Content -Raw app-details.json | ConvertFrom-Json; ` + $ClientId = $Details.client_id; ` + $ClientSecret = $Details.client_secret; ` + $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; ` + $Secret = [System.Convert]::ToHexString([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(64)).ToLower(); ` + Set-Content -Path .env -Value "AUTH0_DOMAIN=$Domain"; ` + Add-Content -Path .env -Value "AUTH0_CLIENT_ID=$ClientId"; ` + Add-Content -Path .env -Value "AUTH0_CLIENT_SECRET=$ClientSecret"; ` + Add-Content -Path .env -Value "AUTH0_SECRET=$Secret"; ` + Add-Content -Path .env -Value "AUTH0_REDIRECT_URI=http://localhost:5000/callback"; ` + Remove-Item app-details.json; ` + Write-Host "✅ Auth0 app created and .env file generated successfully!" + ``` + + + + + + Before you start, create a `.env` file in your project root: + + ```bash .env + # 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 + openssl rand -hex 64 + ``` + + + **Important:** Never commit your `.env` file to version control. Add it to `.gitignore`. + + + + + + Add the Auth0 client code to `auth.py`: + + ```python auth.py + import os + from auth0_server_python.auth_server.server_client import ServerClient + from dotenv import load_dotenv + + load_dotenv() + + # Initialize the Auth0 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'), + authorization_params={ + 'scope': 'openid profile email', + 'audience': os.getenv('AUTH0_AUDIENCE', '') # Optional: for API access + } + ) + ``` + + + This configuration loads your Auth0 credentials from environment variables for security. The `ServerClient` handles OAuth2/OIDC flows automatically. + + + + Add the application code to `app.py`: + + ```python app.py + from flask import Flask, redirect, render_template, request, url_for + from auth import auth0 + + app = Flask(__name__) + app.secret_key = 'your-flask-secret-key-change-in-production' + + @app.route('/') + async def index(): + """Home page - shows login button or user profile""" + user = await auth0.get_user() + return render_template('index.html', user=user) + + @app.route('/login') + async def login(): + """Redirect to Auth0 login""" + authorization_url = await auth0.start_interactive_login() + return redirect(authorization_url) + + @app.route('/callback') + async def callback(): + """Handle Auth0 callback after login""" + try: + result = await auth0.complete_interactive_login(request.url) + return redirect(url_for('index')) + except Exception as e: + return f"Authentication error: {str(e)}", 400 + + @app.route('/profile') + async def profile(): + """Protected route - shows user profile""" + user = await auth0.get_user() + + if not user: + return redirect(url_for('login')) + + return render_template('profile.html', user=user) + + @app.route('/logout') + async def logout(): + """Logout and redirect to Auth0 logout""" + logout_url = await auth0.logout() + return redirect(logout_url) + + if __name__ == '__main__': + app.run(debug=True, port=5000) + ``` + + + Flask 2.0+ supports `async def` routes, which is required for the async Auth0 SDK methods. If you're using an older Flask version, consider upgrading or using Quart. + + + + + Add the home page template to `templates/index.html`: + + ```html templates/index.html + + + + + + Flask + Auth0 + + + +
+
+ +

Flask + Auth0

+ + {% if user %} +
+

✅ Successfully logged in!

+ + View Full Profile + Log Out +
+ {% else %} +
+

Welcome! Please log in to access your protected content.

+ Log In +
+ {% endif %} +
+
+ + + ``` +
+ + Add the profile page template to `templates/profile.html`: + + ```html templates/profile.html + + + + + + User Profile - Flask + Auth0 + + + +
+
+ +

User Profile

+ +
+ {% if user.picture %} + Profile + {% endif %} + +
+

{{ user.name }}

+ + +
+

Profile Information

+
+
User ID:
+
{{ user.sub }}
+ + {% if user.nickname %} +
Nickname:
+
{{ user.nickname }}
+ {% endif %} + + {% if user.updated_at %} +
Last Updated:
+
{{ user.updated_at }}
+ {% endif %} +
+
+
+
+ + +
+
+ + + ``` +
+ + Create `static/style.css` with modern Auth0-branded styling: + + ```css static/style.css +@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: 'Inter', sans-serif; + background: linear-gradient(135deg, #1a1e27 0%, #2d313c 100%); + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + padding: 20px; +} + +.container { + width: 100%; + max-width: 600px; +} + +.card { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + padding: 3rem; + animation: fadeInScale 0.6s ease-out; +} + +@keyframes fadeInScale { + from { + opacity: 0; + transform: scale(0.95); + } + to { + opacity: 1; + transform: scale(1); + } +} + +.logo { + width: 160px; + margin: 0 auto 2rem; + display: block; + animation: slideDown 0.8s ease-out; +} + +@keyframes slideDown { + from { + opacity: 0; + transform: translateY(-30px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +h1 { + font-size: 2.5rem; + font-weight: 700; + text-align: center; + margin-bottom: 2rem; + color: #f7fafc; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); +} + +h2 { + font-size: 1.8rem; + font-weight: 600; + margin: 0.5rem 0; + color: #f7fafc; +} + +h3 { + font-size: 1.3rem; + font-weight: 600; + margin-top: 1.5rem; + margin-bottom: 1rem; + color: #cbd5e0; +} + +.logged-in, .logged-out { + text-align: center; +} + +.logged-out p { + font-size: 1.2rem; + color: #cbd5e0; + margin-bottom: 2rem; + line-height: 1.6; +} + +.success { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + margin-bottom: 1.5rem; +} + +.user-info { + background-color: #2d313c; + border-radius: 15px; + padding: 2rem; + margin: 2rem 0; +} + +.profile-pic { + width: 80px; + height: 80px; + border-radius: 50%; + margin-bottom: 1rem; + border: 3px solid #63b3ed; + object-fit: cover; +} + +.profile-pic-large { + width: 120px; + height: 120px; + border-radius: 50%; + margin-bottom: 1rem; + border: 4px solid #63b3ed; + object-fit: cover; +} + +.user-info p, .email { + color: #a0aec0; + font-size: 1.1rem; +} + +.button { + display: inline-block; + padding: 1rem 2.5rem; + font-size: 1.1rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + text-decoration: none; + text-transform: uppercase; + letter-spacing: 0.08em; + margin: 0.5rem; + background-color: #63b3ed; + color: #1a1e27; + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); +} + +.button:hover { + background-color: #4299e1; + transform: translateY(-3px); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); +} + +.button.logout { + background-color: #fc8181; +} + +.button.logout:hover { + background-color: #e53e3e; +} + +.profile-details { + text-align: center; +} + +.profile-info { + background-color: #2d313c; + border-radius: 15px; + padding: 2rem; + margin-top: 1.5rem; +} + +.profile-data { + margin-top: 2rem; + text-align: left; +} + +.profile-data dl { + display: grid; + grid-template-columns: 150px 1fr; + gap: 1rem; + margin-top: 1rem; +} + +.profile-data dt { + font-weight: 600; + color: #cbd5e0; +} + +.profile-data dd { + color: #a0aec0; + word-break: break-all; +} + +.actions { + margin-top: 2rem; + display: flex; + justify-content: center; + flex-wrap: wrap; +} + +@media (max-width: 600px) { + .card { + padding: 2rem; + } + + h1 { + font-size: 2rem; + } + + .button { + padding: 0.8rem 2rem; + font-size: 1rem; + } + + .logo { + width: 120px; + } + + .profile-data dl { + grid-template-columns: 1fr; + gap: 0.5rem; + } + + .profile-data dt { + margin-top: 1rem; + } +} + ``` + + + Create `requirements.txt` to track your dependencies: + + ```txt requirements.txt +auth0-server-python>=1.0.0b7 +flask>=2.0.0 +python-dotenv>=1.0.0 + ``` + + + This makes it easy to install dependencies in other environments with `pip install -r requirements.txt`. + + + + Start the Flask development server: + + ```bash + python app.py + ``` + + Your app will be available at [http://localhost:5000](http://localhost:5000). The Auth0 SDK handles authentication routes automatically. + +
+ + + **Checkpoint** + + You should now have a fully functional Auth0 login page running on your localhost. Try it out: + 1. Visit [http://localhost:5000](http://localhost:5000) + 2. Click **Log In** + 3. Authenticate with Auth0 + 4. You should be redirected back and see your profile information + -##### By Evan Sims - -This tutorial demonstrates how to add user login to a Python web Application built with the Flask framework and Authlib OAuth library.We recommend that you log in to follow this quickstart with examples configured for your account. - - -{/* -System requirements: Python 3 | Authlib 1.0 | Flask 2.0 - */} - - -**New to Auth?** Learn [How Auth0 works](/docs/get-started/auth0-overview), how it [integrates with Regular Web Applications](/docs/get-started/architecture-scenarios/sso-for-regular-web-apps) and which [protocol](/docs/get-started/authentication-and-authorization-flow) it uses. - - -## Configure Auth0 - -### Get Your Application Keys - -When you signed up for Auth0, a new application was created for you, or you could have created a new one. You will need some details about that application to communicate with Auth0. You can get these details from the [Application Settings](https://manage.auth0.com/#/applications) section in the Auth0 dashboard. - -![App Dashboard](https://cdn2.auth0.com/docs/1.14550.0/media/articles/dashboard/client_settings.png) - -You need the following information: - -* **Domain** -* **Client ID** -* **Client Secret** - - -If you download the sample from the top of this page, these details are filled out for you. - - -### Configure Callback URLs - -A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated. The callback URL for your app must be added to the **Allowed Callback URLs** field in your [Application Settings](https://manage.auth0.com/#/applications). If this field is not set, users will be unable to log in to the application and will get an error. - -If you are following along with the sample project you downloaded from the top of this page, the callback URL you need to add to the **Allowed Callback URLs** field is `http://localhost:3000/callback`. - - -### Configure Logout URLs - -A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the `returnTo` query parameter. The logout URL for your app must be added to the **Allowed Logout URLs** field in your [Application Settings](https://manage.auth0.com/#/applications). If this field is not set, users will be unable to log out from the application and will get an error. - -If you are following along with the sample project you downloaded from the top of this page, the logout URL you need to add to the **Allowed Logout URLs** field is `http://localhost:3000`. - - -## Install dependencies - -For the purposes of this example, we'll be using the [Authlib](https://authlib.org/) OAuth library and [Flask](https://flask.palletsprojects.com/en/2.0.x/). - -Begin by creating a `requirements.txt` file in your project directory: - -```txt lines -# 📁 requirements.txt ----- - -flask>=2.0.3 -python-dotenv>=0.19.2 -authlib>=1.0 -requests>=2.27.1 -``` - - - - - - -You should now run `pip install -r requirements.txt` from your shell to make these dependencies available to your project. - -## Configure your .env file - -Next, create an `.env` file in your project directory. This file will hold your client keys and other configuration details. - -export const codeExample = `# 📁 .env ----- - -AUTH0_CLIENT_ID={yourClientId} -AUTH0_CLIENT_SECRET={yourClientSecret} -AUTH0_DOMAIN={yourDomain} -APP_SECRET_KEY=`; - - - - - - - - -* Generate a suitable string for `APP_SECRET_KEY` using `openssl rand -hex 32` from your shell. - -## Setup your application - -Now you're ready to start writing your application. Create a `server.py` file in your project directory - this file will hold all of your application logic. +--- -Begin by importing all the libraries your application will be making use of: +## Common Issues -```py lines -# 📁 server.py ----- + +dArgumentError"> +**Problem:** You see "MissingRequiredArgumentError: secret" when starting the app -import json -from os import environ as env -from urllib.parse import quote_plus, urlencode +**Cause:** The `AUTH0_SECRET` environment variable is missing or not loaded properly. -from authlib.integrations.flask_client import OAuth -from dotenv import find_dotenv, load_dotenv -from flask import Flask, redirect, render_template, session, url_for -``` +**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 + +back 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 + + +**Problem:** You see "RuntimeError: This event loop is already running" or similar async errors -Next, your application will need to load the configuration `.env` file you made in the previous step: +**Cause:** Flask 2.0+ async support may have issues with certain configurations. -```env lines -# 👆 We're continuing from the steps above. Append this to your server.py file. +**Solution:** -ENV_FILE = find_dotenv() -if ENV_FILE: - load_dotenv(ENV_FILE) +**Option 1: Use Quart (Recommended for production)** +```bash +pip install quart ``` +Update your imports in `app.py`: +```python +from quart import Quart, redirect, render_template, request, url_for - - - - -Now you can configure Flask for your application's needs: - -```py lines -# 👆 We're continuing from the steps above. Append this to your server.py file. - -app = Flask(__name__) -app.secret_key = env.get("APP_SECRET_KEY") +app = Quart(__name__) ``` - - - - - -Finally, you can now configure Authlib to handle your application's authentication with Auth0: - -```py lines -# 👆 We're continuing from the steps above. Append this to your server.py file. - -oauth = OAuth(app) - -oauth.register( - "auth0", - client_id=env.get("AUTH0_CLIENT_ID"), - client_secret=env.get("AUTH0_CLIENT_SECRET"), - client_kwargs={ - "scope": "openid profile email", - }, - server_metadata_url=f'https://{env.get("AUTH0_DOMAIN")}/.well-known/openid-configuration' -) +**Option 2: Ensure Flask 2.0+ is installed** +```bash +pip install --upgrade flask +python --version # Ensure Python 3.9+ ``` +### 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 + source venv/bin/activate # macOS/Linux + # or + venv\Scripts\activate # Windows + ``` +2. Install the SDK: + ```bash + pip install auth0-server-python flask python-dotenv + ``` +3. Verify installation: + ```bash + pip list | grep auth0 + ``` +### Session/Cookie Errors -You can learn more about the configuration options available for Authlib's OAuth `register()` method from [their documentation.](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) - -## Setup your routes - -For this demonstration, we'll be adding 4 routes for your application: your login, callback, logout and home routes. - -### Triggering authentication with /login - -When visitors to your app visit the `/login` route, they'll be redirected to Auth0 to begin the authentication flow. - -```py lines -# 👆 We're continuing from the steps above. Append this to your server.py file. - -@app.route("/login") -def login(): - return oauth.auth0.authorize_redirect( - redirect_uri=url_for("callback", _external=True) - ) -``` +**Problem:** Login works but user session is not persisted between requests +**Cause:** By default, the SDK uses in-memory storage which doesn't persist across requests in production. +**Solution:** For production, implement custom storage adapters (Redis, PostgreSQL) or use the SDK's built-in stateless cookie storage. See the "Advanced Usage" section for storage configuration. +--- - - -### Finalizing authentication with /callback - -After your users finish logging in with Auth0, they'll be returned to your application at the `/callback` route. This route is responsible for actually saving the session for the user, so when they visit again later, they won't have to sign back in all over again. - -```py lines -# 👆 We're continuing from the steps above. Append this to your server.py file. - -@app.route("/callback", methods=["GET", "POST"]) -def callback(): - token = oauth.auth0.authorize_access_token() - session["user"] = token - return redirect("/") +## Advanced Usage + + +Create a decorator to protect routes that require authentication: + +Add to `app.py`: +```python +from functools import wraps + +def require_auth(f): + """Decorator to protect routes requiring authentication""" + @wraps(f) + async def decorated_function(*args, **kwargs): + user = await auth0.get_user() + if not user: + return redirect(url_for('login')) + return await f(*args, **kwargs) + return decorated_function + +# Use the decorator +@app.route('/protected') +@require_auth +async def protected(): + user = await auth0.get_user() + return f"Welcome to the protected area, {user['name']}!" ``` - - - - - - -### Clearing a session with /logout - -As you might expect, this route handles signing a user out from your application. It will clear the user's session in your app, and briefly redirect to Auth0's logout endpoint to ensure their session is completely clear, before they are returned to your home route (covered next.) - -```py lines -# 👆 We're continuing from the steps above. Append this to your server.py file. - -@app.route("/logout") -def logout(): - session.clear() - return redirect( - "https://" + env.get("AUTH0_DOMAIN") - + "/v2/logout?" - + urlencode( - { - "returnTo": url_for("home", _external=True), - "client_id": env.get("AUTH0_CLIENT_ID"), - }, - quote_via=quote_plus, + + + +If you need to call a protected API, retrieve an access token: + +```python +@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' ) - ) -``` - - - - - - -### There's no place like /home - -Last but not least, your home route will serve as a place to either render an authenticated user's details, or offer to allow visitors to sign in. - -```py lines -# 👆 We're continuing from the steps above. Append this to your server.py file. - -@app.route("/") -def home(): - return render_template("home.html", session=session.get('user'), pretty=json.dumps(session.get('user'), indent=4)) + + # 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 ``` + +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 + authorization_params={ + 'scope': 'openid profile email offline_access', + 'audience': os.getenv('AUTH0_AUDIENCE') + } + ``` + + + +For production environments, configure Redis or PostgreSQL for session storage: +**Redis Example:** +```python auth.py +import redis.asyncio as redis +from auth0_server_python.stores.redis_state_store import RedisStateStore +# Initialize Redis +redis_client = redis.from_url(os.getenv('REDIS_URL', 'redis://localhost:6379')) -### Server instantiation - -Finally, you'll need to add some small boilerplate code for Flask to actually run your app and listen for connections. - -```py lines -# 👆 We're continuing from the steps above. Append this to your server.py file. - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=env.get("PORT", 3000)) -``` - - - - - - -## Add templates - -Now we just need to create the simple template files used in the routes about (during `render_template()` calls). - -Create a new sub-directory in your project folder named `templates`, and create one file within: `home.html`. You can paste the content from the two fields below into the `home.html` file, respectfully: - -```html lines -# 📁 templates/home.html ----- +# Configure storage +state_store = RedisStateStore( + secret=os.getenv('AUTH0_SECRET'), + redis_client=redis_client +) - - - - Auth0 Example - - - {% if session %} -

Welcome {{session.userinfo.name}}!

-

Logout

-
{{pretty}}
- {% else %} -

Welcome Guest

-

Login

- {% endif %} - - +auth0 = ServerClient( + # ... other config ... + state_store=state_store +) ``` - - - - - -## Run your application - -You're ready to run your application! From your project directory, open a shell and use: - -```bash lines -python3 server.py + +Custom storage adapters require implementing the `StateStore` interface. Refer to the [SDK documentation](https://github.com/auth0/auth0-server-python) for details. + +
+ + + +Implement comprehensive error handling for production: + +```python +from auth0_server_python.error import ApiError, AccessTokenError, MissingTransactionError + +@app.route('/callback') +async def callback(): + try: + result = await auth0.complete_interactive_login(request.url) + return redirect(url_for('index')) + except MissingTransactionError: + # State expired or invalid - restart login + return redirect(url_for('login')) + except ApiError as e: + # Auth0 API error - show user-friendly message + return render_template('error.html', + error=f"Authentication failed: {e.description}"), 400 + except Exception as e: + # Unexpected error + app.logger.error(f"Login error: {str(e)}") + return "An unexpected error occurred. Please try again.", 500 ``` + +--- +## Additional Resources + + + + Complete SDK documentation and API reference + + + Official Flask framework documentation + + + Async-compatible Flask alternative + + + Brand your login page to match your app + + + Enable login with Google, Facebook, GitHub + + + Get help from the Auth0 community + + + + - - - -Your application should now be ready to open from your browser at `http://localhost:3000`. - - -##### What can you do next? - - - - - - - - - -
Configure other identity providersEnable multifactor authentication
Learn about attack protectionLearn about rules
-[Edit on GitHub](https://github.com/auth0/docs/edit/master/articles/quickstart/native/flutter/01-login.md) -
\ No newline at end of file diff --git a/main/docs/quickstart/webapp/python/interactive.mdx b/main/docs/quickstart/webapp/python/interactive.mdx deleted file mode 100644 index 2835e72af6..0000000000 --- a/main/docs/quickstart/webapp/python/interactive.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -mode: wide -description: This guide demonstrates how to integrate Auth0 with a Python Flask application using the Authlib SDK. -sidebarTitle: Python -title: Add Login to Your Python Flask Application ---- -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Server from "/snippets/quickstart/webapp/python/server.py.mdx"; -import Home from "/snippets/quickstart/webapp/python/home.html.mdx"; - -import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; - -import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; - - - -export const sections = [ - { id: "configure-auth0", title: "Configure Auth0" }, - { id: "install-dependencies", title: "Install dependencies" }, - { id: "configure-your-env-file", title: "Configure your .env file" }, - { id: "setup-your-application", title: "Setup your application" }, - { id: "setup-your-routes", title: "Setup your routes" }, - { id: "add-templates", title: "Add templates" }, - { id: "run-your-application", title: "Run your application" } -] - - - - Auth0 allows you to add authentication and gain access to user profile information in your application. This guide - demonstrates how to integrate Auth0 with a Python [Flask](https://flask.palletsprojects.com/) application using the [Authlib](https://authlib.org/) SDK. - -
- To use Auth0 services, you’ll need to have an application set up in the Auth0 Dashboard. The Auth0 application is - where you will configure how you want authentication to work for the project you are developing. - - ### Configure an application - - Use the interactive selector to create a new Auth0 application or select an existing application that represents - the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID - that your application code will use to call Auth0 APIs through the SDK. - - Any settings you configure using this quickstart will automatically update for your Application in the [Dashboard](https://manage.auth0.com/#/), which is where you - can manage your Applications in the future. - - If you would rather explore a complete configuration, you can view a sample application instead. - - ### Configure Callback URLs - - A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have - authenticated. If not set, users will not be returned to your application after they log in. - - - If you are following along with our sample project, set this to - `http://localhost:3000/callback`. - - - ### Configure Logout URLs - - A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged - out. If not set, users will not be able to log out from your application and will receive an error. - - - If you are following along with our sample project, set this to `http://localhost:3000`. - -
- -
- Create a `requirements.txt` file in your project directory: - - ```txt lines - # 📁 requirements.txt ----- - flask>=2.0.3 - python-dotenv>=0.19.2 - authlib>=1.0 - requests>=2.27.1 - ``` - - - Run the following command from your shell to enable these dependencies in your project: - - ```bash lines - pip install -r requirements.txt - ``` - -
- -
- Next, create an `.env` file in your project directory. This file will hold your client keys and other - configuration details. - - ```env lines - # 📁 .env ----- - AUTH0_CLIENT_ID={yourClientId} - AUTH0_CLIENT_SECRET={yourClientSecret} - AUTH0_DOMAIN={yourDomain} - APP_SECRET_KEY= - ``` - - - - Generate a string for `APP_SECRET_KEY`using `openssl rand -hex 32`from your shell. -
- -
- Next, set up your application. Create a `server.py` file in your project directory - this file will - contain your application logic. - - Import all the libraries your application needs. - - Load the configuration `.env` file you made in the previous step. - - Configure Authlib to handle your application's authentication with Auth0. To learn more about the configuration - options available for Authlib's OAuth `register()` method from [their documentation.](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) -
- -
- In this example, you will add four routes to the application: login, callback, logout, and home. - - When visitors to your app visit the `/login` route, your application will route them to the Auth0 - login page. - - After your users log in with Auth0, your application will route them to the `/callback` route. This - route saves the session for the user and bypasses the need for them to login again when they return. - - The `/logout` route signs users out from your application. This route clears the user session in your - app and redirects to the Auth0 logout endpoint to ensure the session is no longer saved. Then, the application - redirects the user to your home route. - - Your `/`home route either renders an authenticated user's details or allows visitors to sign in. -
- -
- Next, create the template file used in the home route (during `render_template()` calls). - - Create a new sub-directory in your project folder named `templates`, and create `home.html` - in the directory. Paste the content from the right into that file. -
- -
- To run your application, navigate to the root of your project directory and open a terminal. Run the following - command: - - ```bash lines - python3 server.py - ``` - - - ##### Checkpoint - - Visit [http://localhost:3000](http://localhost:3000/) to verify. You should find a login button routing to - Auth0 for login, then back to your application to see your profile information. - -
- - ## Next Steps - - Excellent work! If you made it this far, you should now have login, logout, and user profile information running in your application. - - This concludes our quickstart tutorial, but there is so much more to explore. To learn more about what you can do with Auth0, check out: - - * [Auth0 Dashboard](https://manage.auth0.com/dashboard/us/dev-gja8kxz4ndtex3rq) - Learn how to configure and manage your Auth0 tenant and applications - * [auth0-python SDK](https://github.com/auth0/auth0-python) - Explore the SDK used in this tutorial more fully - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Discover integrations you can enable to extend Auth0’s functionality -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
From f2df569aae69ab0466c9378d937742450c3b55da Mon Sep 17 00:00:00 2001 From: sanchitmehta94 Date: Wed, 28 Jan 2026 01:39:39 +0530 Subject: [PATCH 2/2] updated config file --- main/docs.json | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/main/docs.json b/main/docs.json index ed8c70ebfb..9cab25495d 100644 --- a/main/docs.json +++ b/main/docs.json @@ -5025,7 +5025,7 @@ "pages": [ "docs/fr-ca/quickstart/webapp/nextjs/interactive", "docs/fr-ca/quickstart/webapp/express/interactive", - "docs/fr-ca/quickstart/webapp/python/index", + "docs/fr-ca/quickstart/webapp/python/interactive", "docs/fr-ca/quickstart/webapp/django/interactive", "docs/fr-ca/quickstart/webapp/golang/interactive", "docs/fr-ca/quickstart/webapp/java/interactive", @@ -7372,7 +7372,7 @@ "pages": [ "docs/ja-jp/quickstart/webapp/nextjs/interactive", "docs/ja-jp/quickstart/webapp/express/interactive", - "docs/ja-jp/quickstart/webapp/python/index", + "docs/ja-jp/quickstart/webapp/python/interactive", "docs/ja-jp/quickstart/webapp/django/interactive", "docs/ja-jp/quickstart/webapp/golang/interactive", "docs/ja-jp/quickstart/webapp/java/interactive", @@ -23470,6 +23470,10 @@ "source": "/docs/goog-clientid", "destination": "https://marketplace.auth0.com/integrations/google-social-connection" }, + { + "source": "/docs/quickstart/webapp/python/interactive", + "destination": "/docs/quickstart/webapp/python" + }, { "source": "/docs/connections/social/github", "destination": "https://marketplace.auth0.com/integrations/github-social-connection"