Prerequisites: Before you begin, ensure you have the following installed:
- Python 3.9 or higher
- pip or Poetry package manager
- jq - Required for Auth0 CLI setup
- Your preferred code editor
Get Started
This guide demonstrates how to integrate Auth0 with any new or existing Python API built with Flask.1
Create a new Flask project
Create a new directory for your Flask API:Create a virtual environment and activate it:
2
Install dependencies
Create a Install the dependencies:
requirements.txt file with the following dependencies:requirements.txt
3
Setup your Auth0 API
Next up, you need to create a new API on your Auth0 tenant and configure your application.You can choose to do this automatically by running a CLI command or do it manually via the Dashboard:
- Dashboard
- CLI
- Go to the Auth0 Dashboard → Applications → APIs
- Click Create API
- Enter your API details:
- Name:
My Flask API - Identifier:
https://my-flask-api(this will be your audience) - Signing Algorithm: RS256
- Name:
- Click Create
- Copy your Domain from the Dashboard (found under Applications → Applications → [Your App] → Settings)
- Copy the Identifier you just created (this is your audience)
Your Domain should not include
https:// - use only the domain name (e.g., your-tenant.auth0.com).The Audience (API Identifier) is a unique identifier for your API and can be any valid URI.4
Define API permissions
Configure permissions (scopes) for your API to control access to specific resources:
- In the Auth0 Dashboard, navigate to Applications → APIs
- Select your API (
My Flask API) - Go to the Permissions tab
- Click Add Permission
- Add the following permission:
- Permission (Scope):
read:messages - Description:
Read messages
- Permission (Scope):
- Click Add
Permissions define what actions can be performed on your API. You can add multiple permissions like
write:messages, delete:messages, etc. The /api/private-scoped endpoint in this quickstart requires the read:messages permission.5
Configure the Auth0 client
If you used the CLI method in Step 3, your
.env file was automatically created. Skip to creating the app.py file below..env file in your project root to store your Auth0 configuration:.env
app.py file and configure the Auth0 API client:app.py
5
Create protected routes
Add a decorator for protecting routes and create public and private endpoints:
app.py
6
Run your API
Start your Flask application:Your API is now running on
http://localhost:5000.CheckpointYou should now have a fully functional Auth0-protected Flask API running on your localhost with three endpoints:
/api/public- Accessible without authentication/api/private- Requires a valid Auth0 access token/api/private-scoped- Requires authentication and theread:messagespermission
Test Your API
To test your protected endpoints, you need an access token.Get a test token
- Go to the Auth0 Dashboard
- Navigate to Applications → APIs
- Select your API
- Go to the Test tab
- Copy the access token
Make a request
Test the public endpoint (no token required):YOUR_ACCESS_TOKEN with the token you copied from the Auth0 Dashboard.
Advanced Usage
Validating Custom Claims
Validating Custom Claims
Require specific claims to be present in the access token:
DPoP Authentication
DPoP Authentication
For enhanced security, enable DPoP (Demonstrating Proof-of-Possession). DPoP enhances OAuth 2.0 by binding access tokens to cryptographic keys.
The
verify_request() method automatically detects whether the request uses Bearer or DPoP authentication. When DPoP is used, it validates both the access token and the DPoP proof according to RFC 9449.Scope-Based Authorization
Scope-Based Authorization
Error Handling Best Practices
Error Handling Best Practices
Implement comprehensive error handling with specific error types:
All authentication errors extend from
BaseAuthError, which provides methods like get_status_code(), get_headers(), and get_error_code() for proper HTTP responses with WWW-Authenticate headers.Using Before-Request Middleware
Using Before-Request Middleware
For applications where most endpoints require authentication, use Flask’s
before_request to validate tokens globally:Common Issues
401 Unauthorized - Invalid audience
401 Unauthorized - Invalid audience
401 Unauthorized - Invalid issuer
401 Unauthorized - Invalid issuer
Configuration values not found
Configuration values not found
Symptom:
None values or environment variable errorsCause: Environment variables not loaded or .env file not foundSolution:- Ensure
.envfile exists in your project root - Verify
load_dotenv()is called before accessingos.getenv() - Check that variable names match exactly (case-sensitive)
Flask async support errors
Flask async support errors
Symptom:
RuntimeError: This event loop is already running or similar async errorsCause: Using async routes without Flask 3.0+ or mixing sync/async incorrectlySolution:- Upgrade to Flask 3.0 or higher:
pip install --upgrade flask - Ensure all route handlers using
api_clientare declared asasync def - Don’t use
asyncio.run()within route handlers
Token expired errors
Token expired errors
Symptom:
VerifyAccessTokenError: Token is expiredCause: The access token has passed its expiration timeSolution:- Request a new token from the Auth0 Dashboard Test tab
- Implement token refresh in your client application
- Tokens from the Dashboard are typically valid for 24 hours
Missing Authorization header
Missing Authorization header
Additional Resources
SDK Documentation
Complete SDK documentation and API reference
Flask Documentation
Official Flask framework documentation
Auth0 Dashboard
Manage your Auth0 tenant and APIs
API Authentication Guide
Learn about access tokens and API security
DPoP Documentation
Learn about proof-of-possession security
Community Forum
Get help from the Auth0 community