Python

You can get started by either downloading the seed project or if you would like to add Auth0 to an existing application you can follow the tutorial steps.

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Python 2.7, 3.5.1
  • Flask 0.10.1 and up
  • Requests 2.3.0 and up
Show requirements

Specify the Callback URLs

For security purposes, you must add the callback URL of your app to your Client Settings.

Your callback URL is currently set to:

https://YOUR_APP/callback

In this case, the callbackURL should look something like:

http://yourUrl/callback

Add the Dependencies

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

flask
requests
auth0-python

This example uses flask but it could work with any server

Trigger Login With auth0.js

Now, you can use Auth0.js to call the authorize endpoint of the Authentication API and redirect your users to our Hosted Login page. This way, you will be implementing the Authorization Code grant flow, so you will obtain a code.

<script src="https://cdn.auth0.com/js/auth0/8.8/auth0.min.js"></script>
// public/app.js

$(document).ready(function() {
  var auth = new auth0.WebAuth({
    domain: 'YOUR_AUTH0_DOMAIN',
    clientID: 'YOUR_CLIENT_ID'
   });


    $('.btn-login').click(function(e) {
      e.preventDefault();
      auth.authorize({
        audience: 'https://' + 'YOUR_AUTH0_DOMAIN' + '/userinfo',
        scope: 'openid profile',
        responseType: 'code',
        redirectUri: 'https://YOUR_APP/callback'
      });
    });
});  

The redirectUri specified in the constructor must match the URL specified in the previous step.

Add the Auth0 Callback Handler

You'll need to create a callback handler that Auth0 will call once it redirects to your app. This handler exchanges the code we have obtained previously for an access_token and an id_token. For that, you can do the following:

# server.py

import os
import json

from auth0.v3.authentication import GetToken
from auth0.v3.authentication import Users
from dotenv import load_dotenv
from flask import Flask
from flask import redirect
from flask import render_template
from flask import request
from flask import send_from_directory
from flask import session

# Here we're using the /callback route.
@app.route('/callback')
def callback_handling():
    code = request.args.get('code')
    get_token = GetToken('YOUR_AUTH0_DOMAIN')
    auth0_users = Users('YOUR_AUTH0_DOMAIN')
    token = get_token.authorization_code('YOUR_CLIENT_ID',
                                         'YOUR_CLIENT_SECRET', code, 'https://YOUR_APP/callback')
    user_info = auth0_users.userinfo(token['access_token'])
    session['profile'] = json.loads(user_info)
    return redirect('/dashboard')

Access User Information

You can access the user information via the profile you stored in the session on step 2

@app.route("/dashboard")
@requires_auth
def dashboard():
    return render_template('dashboard.html', user=session['profile'])

<div>
  <img class="avatar" src="{{user['picture']}}"/>
  <h2>Welcome {{user['nickname']}}</h2>
</div>

Click here to check all the information that the userinfo hash has.

Logout

You can implement logout by clearing a session and redirecting to logout endpoint.

@app.route('/logout')
def logout():
    session.clear()
    parsed_base_url = urlparse('https://YOUR_APP/callback')
    base_url = parsed_base_url.scheme + '://' + parsed_base_url.netloc
    return redirect('https://%s/v2/logout?returnTo=%s&client_id=%s' % ('YOUR_AUTH0_DOMAIN', base_url, 'YOUR_CLIENT_ID'))

Optional Steps

Check if the user is authenticated

You can add the following annotation to your Flask app to check if the user is authenticated. Note that you should import wraps first, adding the following line to your file from functools import wraps.

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
Use Auth0 for FREECreate free Account