MCPInstall

auth0-flask

Use when adding session-based login, logout, or user profile to a Flask web application. Integrates auth0-server-python — use even if the user says "add login to my Flask app" or "protect my Flask routes".

Installs
411
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/auth0/agent-skills --skill auth0-flask
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads auth0-flask automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Auth0 Flask Web App Integration

Add login, logout, and user profile to a Flask web application using auth0-server-python.


Prerequisites

  • Flask application
  • Auth0 Regular Web Application configured (not an API — must be an Application)
  • If you don't have Auth0 set up yet, use the auth0-quickstart skill first

When NOT to Use

  • Python APIs with JWT Bearer validation — Use auth0-fastapi-api for FastAPI, or see the Django REST Framework quickstart
  • FastAPI web app with login/logout UI — No dedicated skill yet; see the FastAPI quickstart
  • Single Page Applications — Use auth0-react, auth0-vue, or auth0-angular for client-side auth
  • Next.js applications — Use auth0-nextjs which handles both client and server
  • Node.js web apps — Use auth0-express or auth0-fastify for session-based auth

Quick Start Workflow

1. Install SDK

pip install auth0-server-python "flask[async]" python-dotenv

Critical: You must install flask[async] (not just flask). The [async] extra installs asgiref which is required for Flask 2.0+ to support async def route handlers. Without it, async routes will not work. In requirements.txt, use flask[async]>=2.0.0.

2. Configure Environment

Create .env:

AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_CLIENT_ID=your_client_id
AUTH0_CLIENT_SECRET=your_client_secret
AUTH0_SECRET=your_generated_app_secret
AUTH0_REDIRECT_URI=http://localhost:5000/callback

AUTH0_DOMAIN is your Auth0 tenant domain (without https://). AUTH0_CLIENT_ID and AUTH0_CLIENT_SECRET come from your Auth0 Application settings. AUTH0_SECRET is used for encrypting session data — generate with openssl rand -hex 64.

3. Configure Auth0 Dashboard

In your Auth0 Application settings:

  • Allowed Callback URLs: http://localhost:5000/callback
  • Allowed Logout URLs: http://localhost:5000

4. Create Auth Module

Create auth.py to initialize the ServerClient with Flask session-based stores. The stores use Flask's built-in session (cookie-based by default) for a stateless setup — no external database needed:

import os
from flask import session as flask_session
from auth0_server_python.auth_server.server_client import ServerClient
from auth0_server_python.auth_types import StateData, TransactionData
from auth0_server_python.store import StateStore, TransactionStore
from dotenv import load_dotenv

load_dotenv()  # Uses .env by default; pass load_dotenv(".env.local") if credentials are in .env.local


class FlaskSessionStateStore(StateStore):
    """State store that uses Flask's session for persistence."""

    def __init__(self, secret: str):
        super().__init__({"secret": secret})

    async def set(self, identifier, state, remove_if_expires=False, options=None):
        data = state.dict() if hasattr(state, "dict") else state
        flask_session[identifier] = self.encrypt(identifier, data)

    async def get(self, identifier, options=None):
        data = flask_session.get(identifier)
        if data is None:
            return None
        decrypted = self.decrypt(identifier, data)
        # Ensure to not return a dict, as the underlying SDK expects a StateData instance, not a dict
        return StateData(**decrypted) if isinstance(decrypted, dict) else decrypted

    async def delete(self, identifier, options=None):
        flask_session.pop(identifier, None)

    async def delete_by_logout_token(self, claims, options=None):
        pass


class FlaskSessionTransactionStore(TransactionStore):
    """Transaction store that uses Flask's session for persistence."""

    def __init__(self, secret: str):
        super().__init__({"secret": secret})

    async def set(self, identifier, state, remove_if_expires=False, options=None):
        data = state.dict() if hasattr(state, "dict") else state
        flask_session[identifier] = self.encrypt(identifier, data)

    async def get(self, identifier, options=None):
        data = flask_session.get(identifier)
        if data is None:
            return None
        decrypted = self.decrypt(identifier, data)
        # Ensure to not return a dict, as the underlying SDK expects a TransactionData instance, not a dict
        return TransactionData(**decrypted) if isinstance(decrypted, dict) else decrypted

    async def delete(self, identifier, options=None):
        flask_session.pop(identifier, None)


secret = os.getenv("AUTH0_SECRET")

auth0 = ServerClient(
    domain=os.getenv("AUTH0_DOMAIN"),
    client_id=os.getenv("AUTH0_CLIENT_ID"),
    client_secret=os.getenv("AUTH0_CLIENT_SECRET"),
    secret=secret,
    redirect_uri=os.getenv("AUTH0_REDIRECT_URI"),
    state_store=FlaskSessionStateStore(secret=secret),
    transaction_store=FlaskSessionTransactionStore(secret=secret),
    authorization_params={"scope": "openid profile email"},
)

Create one ServerClient instance and reuse it. Never hardcode credentials — always use environment variables.

How this works: Flask's default session is cookie-based (stateless). The SDK encrypts session data (tokens, user profile) with JWE before storing it in the session, so data is both signed and encrypted in the cookie. No server-side database is required.

No store_options or before_request needed: The SDK supports passing store_options (e.g. request/response objects) to store methods. Since these stores use flask.session — which is globally available during a request — they don't need anything from store_options, so you can call SDK methods without passing it. If you implement a custom store that manages cookies directly (instead of using flask.session), you would need to reintroduce store_options with {"request": request, "response": response}.

Cookie size note: Stateless sessions store all data in a cookie (~4KB limit). For most apps this is sufficient. If you store large amounts of session data or hit cookie size limits, switch to stateful setup.

5. Configure Flask App

In app.py, set up Flask with the secret key and session configuration:

import os
from flask import Flask, redirect, request
from auth import auth0
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)
app.secret_key = os.getenv("AUTH0_SECRET")
app.config.update(
    SESSION_COOKIE_SECURE=False,  # Set to True in production (requires HTTPS)
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SAMESITE="Lax",
)

Critical: app.secret_key must be set for Flask session management. Without it, sessions won't work.

For production: Set SESSION_COOKIE_SECURE=True when deploying with HTTPS. Leaving it as False in production allows session cookies to be sent over unencrypted connections.

6. Add Home Route

@app.route("/")
async def home():
    user = await auth0.get_user()
    if user:
        return f"Hello, {user['name']}! <a href='/profile'>Profile</a> | <a href='/logout'>Logout</a>"
    return "Welcome! <a href='/login'>Login</a>"

7. Add Login Route

@app.route("/login")
async def login():
    authorization_url = await auth0.start_interactive_login()
    return redirect(authorization_url)

start_interactive_login() returns a URL string pointing to Auth0's Universal Login page. You must wrap it in redirect(). Authorization params (scope, redirect_uri) are already configured on the ServerClient.

8. Add Callback Route

@app.route("/callback")
async def callback():
    try:
        await auth0.complete_interactive_login(str(request.url))
        return redirect("/")
    except Exception as e:
        return f"Authentication error: {str(e)}", 400

Pass str(request.url) as the first argument — this is the full callback URL including the authorization code query parameters. Always wrap in try/except since the token exchange can fail (e.g. expired code, CSRF mismatch).

9. Add Profile Route (Protected)

@app.route("/profile")
async def profile():
    user = await auth0.get_user()
    if user is None:
        return redirect("/login")
    return (
        f"<h1>{user['name']}</h1>"
        f"<p>Email: {user['email']}</p>"
        f"<img src='{user['picture']}' alt='{user['name']}' width='100' />"
        f"<p><a href='/logout'>Logout</a></p>"
    )

get_user() returns the user's profile from the session, or None if not logged in.

10. Add Logout Route

@app.route("/logout")
async def logout():
    url = await auth0.logout()
    return redirect(url)

logout() returns the Auth0 logout URL. Redirect the user to it.

11. Test the App

flask run

Visit http://localhost:5000/login to start the login flow.


Stateful Setup with Redis

For production apps or when session data exceeds cookie size limits, use Flask-Session with Redis to store sessions server-side. Only a session ID is stored in the cookie.

1. Install Dependencies

pip install flask-session redis

2. Configure Flask-Session

Update app.py to use Redis-backed sessions:

import os
from flask import Flask, redirect, request
from flask_session import Session
from auth import auth0
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)
app.secret_key = os.getenv("AUTH0_SECRET")
app.config.update(
    SESSION_TYPE="redis",
    SESSION_PERMANENT=True,
    SESSION_KEY_PREFIX="auth0:",
    SESSION_COOKIE_SECURE=False,
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SAMESITE="Lax",
)
Session(app)

3. No Store Changes Needed

The same FlaskSessionStateStore and FlaskSessionTransactionStore from auth.py work without modification. Flask-Session transparently switches the flask.session backend from cookies to Redis — the stores continue to use flask.session as before.

Routes are identical to the stateless setup — no code changes needed.


Common Mistakes

MistakeFix
Hardcoding domain, client_id, or client_secret in sourceAlways read from environment variables — never embed credentials in code
Using Authlib or python-jose directlyNot needed; auth0-server-python handles all OAuth/OIDC flows
Using Flask-Login or Flask-DanceNot needed; the SDK manages sessions and authentication
Manually parsing JWTs with jwt.decode()The SDK handles token validation internally
Installing flask without [async] extraMust use flask[async]>=2.0.0 in requirements.txt — without it, async route handlers silently fail
Using synchronous route handlersAll routes calling SDK methods must be async def and use await
Forgetting app.secret_keyRequired for Flask session management — without it, sessions silently fail
Using auth0-fastapi-api in FlaskThat package is for FastAPI APIs — use auth0-server-python for Flask
Passing domain as full URL with https://domain should be the bare domain, e.g. my-tenant.us.auth0.com, not https://my-tenant.us.auth0.com
Not configuring callback URL in Auth0 DashboardMust add http://localhost:5000/callback to Allowed Callback URLs
Returning start_interactive_login() directlyIt returns a URL string, not a response — must wrap in redirect()
Not handling errors in /callbackcomplete_interactive_login() can fail — always wrap in try/except
Calling SDK methods without awaitAll SDK methods are async — forgetting await returns a coroutine instead of the result
Passing options positionally to logout()Use logout(store_options=...) — the first positional parameter is LogoutOptions, not store options
Expecting backchannel logout to workNot supported with cookie-based sessions — delete_by_logout_token is a no-op. Use standard /logout route
Deploying with SESSION_COOKIE_SECURE=FalseMust set to True in production — cookies are sent over HTTP otherwise

Key SDK Methods

All methods are async:

MethodSignaturePurpose
start_interactive_loginawait auth0.start_interactive_login()Returns authorization URL string — wrap in redirect()
complete_interactive_loginawait auth0.complete_interactive_login(str(request.url))Processes the callback URL, exchanges code for tokens
get_userawait auth0.get_user()Returns current session user dict or None
get_access_tokenawait auth0.get_access_token()Returns the access token for calling external APIs
logoutawait auth0.logout()Returns Auth0 logout URL string

Related Skills

  • auth0-express — For server-rendered Express web apps with login/logout sessions
  • auth0-fastify — For Fastify web applications with session-based auth
  • auth0-cli — Manage Auth0 resources from the terminal

Quick Reference

ServerClient configuration:

auth0 = ServerClient(
    domain=os.getenv("AUTH0_DOMAIN"),                    # required
    client_id=os.getenv("AUTH0_CLIENT_ID"),              # required
    client_secret=os.getenv("AUTH0_CLIENT_SECRET"),      # required
    secret=os.getenv("AUTH0_SECRET"),                    # required (encryption secret)
    redirect_uri=os.getenv("AUTH0_REDIRECT_URI"),        # required
    state_store=FlaskSessionStateStore(secret=secret),   # required
    transaction_store=FlaskSessionTransactionStore(secret=secret),  # required
    authorization_params={"scope": "openid profile email"},  # recommended
)

Route protection pattern:

user = await auth0.get_user()
if user is None:
    return redirect("/login")

Environment variables:

  • AUTH0_DOMAIN — your Auth0 tenant domain (e.g. tenant.us.auth0.com)
  • AUTH0_CLIENT_ID — your Application's client ID
  • AUTH0_CLIENT_SECRET — your Application's client secret
  • AUTH0_SECRET — encryption and session secret key
  • AUTH0_REDIRECT_URI — callback URL (e.g. http://localhost:5000/callback)

Detailed Documentation

  • Setup Guide - Automated setup scripts, environment configuration, Auth0 CLI usage
  • Integration Guide - Protected routes, calling APIs, session management, error handling
  • API Reference - Complete ServerClient API, configuration options, store implementation, security

References

FAQ

What does the auth0-flask skill do?

Use when adding session-based login, logout, or user profile to a Flask web application. Integrates auth0-server-python — use even if the user says "add login to my Flask app" or "protect my Flask routes".

How do I install auth0-flask?

Run npx skills add https://github.com/auth0/agent-skills --skill auth0-flask in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/auth0-flask/ (personal) or .claude/skills/auth0-flask/ (project).

Which AI agents can use auth0-flask?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is auth0-flask safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains auth0-flask?

It is published by auth0 in auth0/agent-skills, and it is an official skill from the maker of the technology it covers. It has 411 recorded installs.

More from auth0/agent-skills

View all →

auth0

auth0/agent-skills

Use when adding, fixing, or improving how an app authenticates users or protects an API, or when using or configuring any Auth0 feature — signing users in and out, sessions and tokens, guarding routes and endpoints, MFA, passwordless passkey login (WebAuthn), SSO, Organizations, RBAC, custom domains, Universal Portals for hosted account and organization self-service, or Universal Login branding. Also use to audit a tenant's health, security, and plan fit (CheckMate), to debug why an auth flow fails, to migrate from another auth provider, or to set up the Vercel native integration. Covers any web, mobile, or backend framework and every Auth0 SDK, tool, and API. Use even if the user never mentions Auth0.

Backend & APIs5.3K installs

auth0-quickstart

auth0/agent-skills

Use when adding Auth0 authentication to any app and unsure which SDK or skill to use. Detects the project's framework and routes to the right setup workflow — use this as the entry point even if the user just says "add login to my app" or "set up Auth0" without naming a framework.

OfficialAI & Agents2.7K installs

auth0-nextjs

auth0/agent-skills

Use when adding Auth0 login, logout, protected pages, or middleware to a Next.js application. Supports App Router and Pages Router with @auth0/nextjs-auth0 — use even if the user says "add login to my Next.js app" or "protect my Next.js routes".

OfficialFrontend & Design1.6K installs

auth0-react

auth0/agent-skills

Use when adding Auth0 login, logout, protected routes, or user sessions to a React SPA. Integrates @auth0/auth0-react — use even if the user says "add login to my React app" or "protect my React routes" without naming the SDK.

OfficialFrontend & Design1.5K installs

auth0-react-native

auth0/agent-skills

Use when adding Auth0 login, logout, or biometric auth to a bare React Native app (not Expo). Integrates react-native-auth0 with native deep linking.

OfficialFrontend & Design963 installs

auth0-express

auth0/agent-skills

Use when adding session-based login, logout, or protected routes to an Express.js web application. Integrates express-openid-connect — use even if the user says "add login to my Express app" or "protect my Express routes".

OfficialBackend & APIs816 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs