Python

View on Github

Python

Gravatar for luciano.balmaceda@auth0.com
By Luciano Balmaceda

This tutorial demonstrates how to add user login to a Python web Application built with the Flask framework. We recommend that you log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: Python 2.7, 3.0 and up | Flask 0.10.1 and up | Python-dotenv 0.6.5 and up | Requests 2.3.0 and up | Flask-oauthlib 0.9.4 and up | Six 1.10.0 and up

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 section in the Auth0 dashboard.

App Dashboard

You need the following information:

  • Domain
  • 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 added to 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 added to 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

This example uses Flask and the Authlib OAuth library.

Add the following dependencies to your requirements.txt and run pip install -r requirements.txt.

// /requirements.txt

flask
python-dotenv
requests
authlib
six

Was this helpful?

/

Initialize Authlib

Create a file named server.py, and instantiate an application with your client keys, scopes, and OAuth endpoints.

# /server.py

from functools import wraps
import json
from os import environ as env
from werkzeug.exceptions import HTTPException

from dotenv import load_dotenv, find_dotenv
from flask import Flask
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import session
from flask import url_for
from authlib.integrations.flask_client import OAuth
from six.moves.urllib.parse import urlencode

app = Flask(__name__)

oauth = OAuth(app)

auth0 = oauth.register(
    'auth0',
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    api_base_url='https://YOUR_DOMAIN',
    access_token_url='https://YOUR_DOMAIN/oauth/token',
    authorize_url='https://YOUR_DOMAIN/authorize',
    client_kwargs={
        'scope': 'openid profile email',
    },
)

Was this helpful?

/

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 session.

# /server.py

# Here we're using the /callback route.
@app.route('/callback')
def callback_handling():
    # Handles response from token endpoint
    auth0.authorize_access_token()
    resp = auth0.get('userinfo')
    userinfo = resp.json()

    # Store the user information in flask session.
    session['jwt_payload'] = userinfo
    session['profile'] = {
        'user_id': userinfo['sub'],
        'name': userinfo['name'],
        'picture': userinfo['picture']
    }
    return redirect('/dashboard')

Was this helpful?

/

Trigger Authentication

Add a /login route that uses the Authlib client instance to redirect the user to the login page. Replace YOUR_CALLBACK_URL in the snippet below with the Allowed Callback URL configured for your Application in the Auth0 dashboard.

# /server.py

@app.route('/login')
def login():
    return auth0.authorize_redirect(redirect_uri='YOUR_CALLBACK_URL')

Was this helpful?

/

Create a home.html file in a /templates folder. Add a link to the /login route.

<div class="login-box auth0-box before">
    <img src="https://i.cloudup.com/StzWWrY34s.png" />
    <h3>Auth0 Example</h3>
    <p>Zero friction identity infrastructure, built for developers</p>
    <a class="btn btn-primary btn-lg btn-login btn-block" href="/login">Log In</a>
</div>

Was this helpful?

/

Check if the user is authenticated

Add the following decorator to your Flask app. Use it to decorate methods that require authentication.

# /server.py

def requires_auth(f):
  @wraps(f)
  def decorated(*args, **kwargs):
    if 'profile' not in session:
      # Redirect to Login page here
      return redirect('/')
    return f(*args, **kwargs)

  return decorated

Was this helpful?

/

Display User Information

Add a /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.

# /server.py

@app.route('/dashboard')
@requires_auth
def dashboard():
    return render_template('dashboard.html',
                           userinfo=session['profile'],
                           userinfo_pretty=json.dumps(session['jwt_payload'], indent=4))

Was this helpful?

/

Add a dashboard.html file in a /templates folder to display the user information.

Add a link to allow users to Log Out.

<div class="logged-in-box auth0-box logged-in">
    <h1 id="logo"><img src="//cdn.auth0.com/samples/auth0_logo_final_blue_RGB.png" /></h1>
    <img class="avatar" src="{{userinfo['picture']}}"/>
    <h2>Welcome {{userinfo['name']}}</h2>
    <pre>{{userinfo_pretty}}</pre>
    <a class="btn btn-primary btn-lg btn-logout btn-block" href="/logout">Logout</a>
</div>

Was this helpful?

/

Logout

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.

# /server.py

@app.route('/logout')
def logout():
    # Clear session stored data
    session.clear()
    # Redirect user to logout endpoint
    params = {'returnTo': url_for('home', _external=True), 'client_id': 'YOUR_CLIENT_ID'}
    return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params))

Was this helpful?

/
Use Auth0 for FREE