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 this sample project 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

Add the Dependencies

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

flask
requests

This example uses flask but it could work with any server

Add the Auth0 Callback Handler

You'll need to create a callback handler that Auth0 will call once it redirects to your app. For that, you can do the following:

import os
import json

import requests
from flask import Flask, request, jsonify, session, redirect, render_template, send_from_directory

# Here we're using the /callback route.
@app.route('/callback')
def callback_handling():
  code = request.args.get('code')

  json_header = {'content-type': 'application/json'}

  token_url = "https://{domain}/oauth/token".format(domain='YOUR_AUTH0_DOMAIN')

  token_payload = {
    'client_id':     'YOUR_CLIENT_ID',
    'client_secret': 'YOUR_CLIENT_SECRET',
    'redirect_uri':  'https://YOUR_APP/callback',
    'code':          code,
    'grant_type':    'authorization_code'
  }

  token_info = requests.post(token_url, data=json.dumps(token_payload), headers = json_header).json()

  user_url = "https://{domain}/userinfo?access_token={access_token}" \
      .format(domain='YOUR_AUTH0_DOMAIN', access_token=token_info['access_token'])

  user_info = requests.get(user_url).json()

  # We're saving all user information into the session
  session['profile'] = user_info

  # Redirect to the User logged in page that you want here
  # In our case it's /dashboard
  return redirect('/dashboard')

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

Triggering Login Manually or Integrating Lock

For more information on using Lock see the documentation.

<script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {
    auth: {
      redirectUrl: 'https://YOUR_APP/callback',
      responseType: 'code',
      params: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    }
  });
</script>
<button onclick="lock.show();">Login</button>
<div id="root" style="width: 320px; margin: 40px auto; padding: 10px; border-style: dashed; border-width: 1px; box-sizing: border-box;">
    embedded area
</div>
<script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', {
    container: 'root',
    auth: {
      redirectUrl: 'https://YOUR_APP/callback',
      responseType: 'code',
      params: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    }
  });
  lock.show();
</script>
<script src="https://cdn.auth0.com/js/lock-passwordless-2.2.min.js"></script>
<script>
  var lock = new Auth0LockPasswordless('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN');
  function open() {
    lock.sms({
      callbackURL: 'https://YOUR_APP/callback',
      authParams: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    });
  }
</script>
<button onclick="window.open();">SMS</button>
<script src="https://cdn.auth0.com/js/lock-passwordless-2.2.min.js"></script>
<script>
  var lock = new Auth0LockPasswordless('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN');
  function open() {
    lock.emailcode({
      callbackURL: 'https://YOUR_APP/callback',
      authParams: {
        scope: 'openid email'  // Learn about scopes: https://auth0.com/docs/scopes
      }
    });
  }
</script>
<button onclick="window.open();">Email Code</button>
<button class="signin-google">Sign in with Google (redirect)</button><br>
<button class="signin-google-popup">Sign in with Google (popup)</button><br>
<br><p>--- or ---</p>
<label>Email</label><input type="text" id="email"><br>
<label>Password</label><input type="password" id="password"><br>
<button class="signin-db">Sign in with Email/Password</button>

<script src="https://cdn.auth0.com/w2/auth0-7.1.min.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
  var auth0 = new Auth0({
    domain:         'YOUR_AUTH0_DOMAIN',
    clientID:       'YOUR_CLIENT_ID',
    callbackURL:    'https://YOUR_APP/callback'
  });
  // sign-in with social provider with plain redirect
  $('.signin-google').on('click', function() {
    auth0.signin({connection: 'google-oauth2'}); // use connection identifier
  });
  // sign-in with social provider using a popup (window.open)
  $('.signin-google-popup').on('click', function() {
    auth0.signin({popup: true, connection: 'google-oauth2'},
                function(err, profile, id_token, access_token, state) {
                    /*
                      store the profile and id_token in a cookie or local storage
                        $.cookie('profile', profile);
                        $.cookie('id_token', id_token);
                    */
                });
  });
  $('.signin-db').on('click', function() {
    auth0.signin({
      connection: 'foo',
      username: 'bar',
      password: 'foobar'
    },
    function (err, profile, id_token, access_token, state) {
      /*
          store the profile and id_token in a cookie or local storage
            $.cookie('profile', profile);
            $.cookie('id_token', id_token);
        */
    });
  });
</script>

Note: Please note that the redirectUrl specified in the Auth0Lock constructor must match the URL specified in the previous step

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

Optional steps

Checking 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