This tutorial demonstrates how to add user login to a Python web Application built with the Flask framework. We recommend you to Log in to follow this quickstart with examples configured for your account.
I want to integrate with my app15 minutes
I want to explore a sample app2 minutes
Get a sample configured with your account settings or check it out on Github.
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 section in the Auth0 dashboard.
You need the following information:
- Client ID
- Client Secret
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 whitelisted in the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.
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 whitelisted in the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.
Configure Flask to Use Auth0
Add the Dependencies
Add the following dependencies to your
requirements.txt and run
pip install -r requirements.txt.
Create a file named
server.py, and instantiate an application with your client keys, scopes, and OAuth endpoints.
Add the Callback Handler
This handler exchanges the
code that Auth0 sends to the callback URL for an Access Token and an ID Token.
The Access Token will be used to call the
/userinfo endpoint to get the user profile. After the user information is obtained, store then in the flask
/login route that uses the
Authlib client instance to redirect the user to the login page.
home.html file in a
/template folder. Add a link to the
Check if the user is authenticated
Add the following decorator to your
Flask app. Use it to decorate methods that require authentication.
Display User Information
/dashboard route to
server.py that will render the user information stored in the Flask session.
Decorate it with
@requires_auth. It will only be accessible if the user has been authenticated.
dashboard.html file in a
/template folder to display the user information.
Add a link to allow users to Log Out.
To log the user out, you have to clear the data from the session, and redirect the user to the Auth0 logout endpoint. You can find more information about this in our documentation logout documentation.