Auth
1
Auth0 Links:
https://auth0.com/docs/get-started/auth0-overview
https://developer.auth0.com/resources/code-samples
2
3
User Logs In: You redirect the user to Auth0’s /authorize endpoint (Universal Login). Callback: After successful login, Auth0 redirects the user back to your FastAPI callback endpoint with an authorization code. Your app exchanges the code for tokens (access token, ID token, possibly a refresh token).
Create a Session: Your FastAPI app creates a new session entry in your server-side session store. In that session, you store the tokens and/or user information.
Set a Cookie: You send back a session cookie (which contains a session ID) to the user. The cookie should be HTTP-only, Secure, and have an appropriate SameSite setting.
Subsequent Requests: The user’s browser automatically sends the session cookie. The server retrieves session data by the cookie’s session ID, finds user info/tokens, and checks if the session is valid. Session Expiration: Depending on your configuration, the session ends either when the user logs out or when your specified session timeout is reached.
4
Complete plan:
1. Create and Configure Your Auth0 Tenant
Sign Up or Log In to Auth0
Go to manage.auth0.com and create or access your Auth0 tenant.
Create an Application
Choose the Application type (e.g., Regular Web Application) if you’re serving both front and back-end from FastAPI, or Single Page Application if you have a separate front-end.
Note your Client ID, Client Secret, Domain (e.g.,
your-tenant.us.auth0.com), and set the Callback URLs (e.g.,https://yourapp.com/callback) and Logout URLs.
Create an API (optional but recommended for RBAC)
In the Auth0 Dashboard, go to Applications → APIs → Create API.
Configure the Identifier (e.g.,
https://your-fastapi-api) and set Signing Algorithm toRS256.Enable RBAC: In the API’s Settings tab, toggle Enable RBAC and Add Permissions in the Access Token.
2. Enable and Configure Auth0 Organizations Auth0 Organizations let you separate different groups or tenants under your application. Each organization can have its own branding, membership, and login flow.
Enable Organizations
In the Auth0 Dashboard, go to Organizations (or search “Organizations” in the left sidebar).
Create a new Organization (e.g., “Acme Inc.”).
Set up branding and connection (e.g., email/password, social connections, etc.).
Associate Your Application
Under the Organization’s Settings, add your Auth0 Application to “Associated Applications.”
This ensures that when you prompt a user to log in via a particular Organization, it correctly routes them.
User Invitations (Optional)
You can enable user invitations if you want members to join your organization via email invites.
3. Set Up Auth0 Connections 3.1. Social Logins
Enable Social Connections
In the Auth0 Dashboard, navigate to Authentication → Social.
Toggle providers like Google, Facebook, GitHub, etc.
Configure the client IDs/secrets for each provider.
Associate with Your Application or Organization
Once enabled, go to Applications or Organizations and ensure the chosen social connections are enabled for your app.
3.2. Magic Links (Passwordless Email)
Enable PasswordlessIn the Auth0 Dashboard, go to Authentication → Passwordless.
Choose Email as the connection type (Auth0 supports SMS or Email for passwordless).
Configure Templates and Email ProviderCustomize the email template used for your Magic Link.
Set up an email provider in Auth0 Dashboard → Branding → Email Templates or Email Providers.
Associate the Connection with Your ApplicationIn the Passwordless connection settings, enable your new application.
3.3. Multifactor Authentication (MFA)
Enable MFAIn the Auth0 Dashboard, go to Security → Multi-factor Auth.
Toggle on the factors you want (e.g., SMS, Authenticator app, Email).
PoliciesDecide whether MFA is always required or only for specific risk-based scenarios or user groups.
TestMake sure you test the MFA flow with a test user.
4. Configure RBAC (Roles & Permissions)
Create RolesUnder User Management → Roles, create roles (e.g.,
admin,editor,viewer) relevant to your application.Define PermissionsUnder User Management → Permissions (or within each Role), define permissions (e.g.,
read:products,create:products).Assign Roles to Users or OrganizationsAssign roles to users at the organization level (if using Organizations).
Alternatively, assign roles at the tenant level for general usage.
Note: With RBAC enabled, the access token will contain a permissions array that you can check in your FastAPI routes.5. FastAPI Project Setup
5.1. Install Dependencies
5.2. Add Environment Variables
Store Auth0 configuration in environment variables or a .env file:
6. Session Handling (Server-Side) We’ll use SessionMiddleware from Starlette to create secure, server-based sessions. This approach lets you store tokens on the server and expose only a short-lived session ID in a cookie.
Set Up Session Middleware
Session ExpirationIf
max_ageis set to3600, the session cookie becomes invalid after an hour (unless you implement a sliding expiration mechanism).For advanced scenarios, consider storing session data in Redis or a database with your own custom TTL logic.
7. Implement Auth Flows in FastAPI 7.1. Login (Organization-Aware, Social, or Passwordless) You can prompt a user to log in via different connections or organizations. For example, to log in to a specific organization:
Social Logins: If you have social connections enabled, Auth0’s Universal Login will display them automatically.
Passwordless (Magic Link): If you have passwordless enabled, you’d direct your user to a special login screen or use an Auth0 Passwordless API endpoint.
7.2. Callback After a successful login (via passwordless, social, or email/password), Auth0 redirects the user here with an auth code. Exchange the code for tokens and store them in the session:
7.3. Protected Routes Check the session for tokens. Optionally, verify or refresh them if expired:
7.4. Logout and Session Termination
8. Handling RBAC in Your Routes
Token Contains PermissionsIf RBAC is enabled and “Add Permissions in the Access Token” is toggled, your
access_tokenincludes apermissionsarray.
Check Permissions:
You can abstract this into a reusable dependency in FastAPI to keep your routes clean.9. Security Best Practices
Use HTTPS in Production
Ensure your domain has a valid SSL certificate.
Configure Auth0 to only allow callbacks/logouts over HTTPS.
Secure Cookies
Set
https_only=True,httponly=True(by default) for session cookies.Use
same_site="lax"orstrictdepending on your app’s needs.
Validate and Cache JWKS
For production, always verify tokens with Auth0’s JWKS.
Implement caching so you don’t fetch the JWKS every time.
Libraries like Authlib can handle this gracefully.
Short Token Lifetimes & Refresh Token Rotation
Keep access tokens short-lived (e.g., 5–15 minutes).
Use refresh tokens (securely stored) if your app needs silent re-authentication.
Organization & Tenant-Level Settings
Customize your Universal Login for each organization with branding.
Configure Session Lifetime at the Auth0 tenant or application level to suit your security posture.
Limit Attack Surface
Only enable the Auth0 connections (social/passwordless) you truly need.
Regularly audit which roles/permissions your users and organizations have.
Logging & Monitoring
In Auth0 Dashboard → Monitoring → Logs, track logins, failures, anomalies.
Implement alerts for suspicious activity.
Deployment
Avoid leaking secrets. Keep
AUTH0_CLIENT_SECRETin a secure location (e.g., environment variables in your server, or a secrets manager like AWS Secrets Manager).Always restrict callback/logout URLs to known domains.
10. Summary
Auth0 Setup: Create an Application, optionally an API for RBAC. Enable Organizations, RBAC, MFA, Social Logins, Magic Links as needed in your Auth0 tenant.
FastAPI Setup: Use
SessionMiddlewareto manage session IDs and store access tokens server-side.Login & Callback: Redirect users to Auth0, handle the code exchange, and store tokens in session.
Protected Routes: Check session for valid tokens (verify if needed). Optionally enforce RBAC by checking permissions in the token.
Logout: Clear session + redirect to Auth0 logout.
Security Best Practices: Use HTTPS, secure cookies, short token lifetimes, refresh tokens, and monitor logs.
Organizations: Provide an organizational ID in your authorize calls or deep links, manage membership, and leverage organization-level roles/permissions if required.
By following this end-to-end plan, you’ll have a robust and secure FastAPI application that supports session-based authentication with Auth0, advanced features like RBAC, MFA, Magic Links, Social Logins, and Organizations, all under a best-practices security posture. Be sure to consult Auth0’s official documentation for the latest configuration details and updates.
5
Below is a high-level guide for migrating your existing Postgres users (with bcrypt-hashed passwords) into Auth0. Auth0 offers two main approaches:
Bulk User Import (works well if you can export user data in a supported format and want a “big-bang” migration).
Automatic/Just-in-Time Migration (a more gradual approach using a Custom Database Connection in Auth0).
Which approach you choose depends on your environment, how disruptive you want the migration to be, and whether you can provide hashed passwords in a format Auth0 accepts for bulk import.1. Bulk Import Approach
If you want to do a one-time import of your entire user base (and do not want to rely on external DB lookups at login), you can use Auth0’s Bulk Import feature.
1.1. Check Supported Hashes for Import
Auth0’s bulk import can handle hashed passwords if they match certain formats. Specifically, you’ll need to provide a custom_password_hash object for each user. Auth0 supports bcrypt (and other algorithms) if you provide the correct parameters. The process is detailed in Auth0 docs on Bulk Import Hashed Passwords.
For bcrypt, you typically need:
The
"value"is the existing bcrypt hash from your Postgres DB.Make sure the
"rounds"field matches the actual cost factor you used when hashing.
1.2. Export Users from Postgres
Write a script or query to export your users in a JSON format compatible with Auth0’s bulk import.
For each user, gather the email, any profile info, and the bcrypt hash.
Example single user JSON record:
Combine all users in an array (one JSON object per user).
1.3. Use Auth0 Bulk Import Job
Go to Auth0 Dashboard → User Management → Users → Import Users (or use the Management API).
Upload the JSON file with your exported users.
Auth0 processes the file. If successful, these users are fully migrated. They can now log in through Auth0 directly.
Advantages:
One-time operation.
After import, users are entirely managed in Auth0.
No need to maintain a custom DB connection or rely on your old database for logins.
Disadvantages:
Requires a careful data export in the correct format.
All users appear in Auth0 at once (might conflict if you have an ongoing user signup process in your legacy system).
2. Automatic (Just-in-Time) Migration Approach If you cannot or prefer not to bulk-import hashed passwords in the required format—or if you want a gradual transition—you can use Auth0’s Custom Database Connection feature. With this approach, user credentials remain in your Postgres DB until they log in for the first time. Auth0 will:
Prompt for username/password.
Call a login script you supply (Node.js code in the Auth0 Dashboard).
That script verifies the user’s credentials in your Postgres DB using bcrypt.
If valid, Auth0 creates the user in its own store and subsequently uses Auth0’s store for that user.
Over time, all active users get migrated automatically. Eventually, you can retire your old DB for authentication. 2.1. Set Up a Custom Database Connection
In the Auth0 Dashboard, go to Authentication → Database.
Click + Create DB Connection → Give it a name (e.g.,
my-legacy-db).Under the Custom DB tab, toggle Use my own database.
Enter the Script for “Login” (and optionally “Get User,” “Create,” etc.). This script will be Node.js code that queries your Postgres DB. Auth0 provides a sample:
Adjust the code to match your actual schema (e.g.,
password_hash, your user table name, etc.).Make sure your Postgres connection string is correct.
Under Settings for the Custom DB connection, enable Import Users to Auth0. This triggers the “just-in-time” migration upon the first successful login.
2.2. Configure Your Application to Use This Custom DB
Under Auth0 Dashboard → Applications → [Your App] → Connections, enable your new custom DB connection.
Now, when a user attempts to log in, Auth0 will call your script. If login is successful, the user is “migrated” into Auth0.
Subsequent logins will use Auth0’s internal store for that user, not your Postgres DB.
Advantages:
Gradual, non-disruptive migration (users move only when they log in).
No need to do a big bulk import with hashed password complexities.
Disadvantages:
Requires maintaining an accessible Postgres DB (for old users) until everyone has logged in once.
Slight overhead for the first login of each user as Auth0 calls your script.
3. Handling Bcrypt Hashed Passwords
Both methods support bcrypt.
Bulk Import: Provide the hash in the
custom_password_hashobject.Custom DB: The Node.js login script calls
bcrypt.compareto verify.
4. Post-Migration Considerations
Test Thoroughly: Use a small batch or test environment first.
User Profile Data: Decide which fields (name, roles, etc.) you want to import.
RBAC and Roles: If you plan to use Auth0 RBAC, you may want to assign roles automatically after the user is migrated (via Auth0 Rules or Actions) or do a post-processing step.
Retire Old Auth: Once all (or most) of your users are in Auth0, you can remove old authentication logic from your FastAPI app.
Communication: Let users know about new login processes, especially if you switch to Auth0 Universal Login or introduce new password policies.
5. Choosing the Right Method Use Bulk Import if:
You can export all user data in one shot.
You prefer a clean cutover and can handle temporarily disabling signups (or synchronizing them) during the import.
You can meet Auth0’s required JSON format for hashed passwords.
Use Custom DB (Automatic Migration) if:
You cannot (or prefer not to) do a single big import.
You want to migrate users gradually as they log in.
Your Postgres DB can stay accessible for a while.
In some cases, teams do a hybrid approach: bulk import most users, then have a custom DB fallback for any that might have changed their credentials in the interim, or for newly registered users still in the old system.6. Summary
Bulk Import: Export your users from Postgres, provide a JSON file with
custom_password_hashfor each user (including their bcrypt hash), and import into Auth0 via the Bulk Import Job.Automatic Migration: Create a Custom Database Connection in Auth0, implement a Node.js script that verifies credentials in your Postgres DB, and let Auth0 migrate users on first successful login.
Testing & Validation: Whichever route you choose, test thoroughly in a staging environment with a subset of users.
Post-Migration: Update your FastAPI app to rely on Auth0 for authentication, retire your old auth logic, and handle new signups/logins fully through Auth0 going forward.
Following these steps will help you securely and reliably move your existing user base (with bcrypt-hashed passwords) from Postgres into Auth0.
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Last updated
Was this helpful?