FusionAuth QuickStart for Python Flask

On this page

This QuickStart explains how to add a login page and authentication to a website built with Flask. You'll begin with a simple Flask app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.

This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.

Prerequisites#

This QuickStart requires:

If you use macOS or Windows, you need one of the following container management tools:

  • Docker Desktop
  • OrbStack (to use OrbStack for docker compose commands after installation, run docker context use orbstack)
  • Podman (in the commands below, replace docker with podman)

Create a Simple Flask App#

For this QuickStart, we'll use a Flask app that reads and writes data to a text file:

  1. Create a folder for the app and navigate into it:

    $ mkdir flask-quickstart && cd flask-quickstart
    
  2. Create a virtual environment for the app's dependencies and activate it:

    $ python3 -m venv .venv
    
    $ source .venv/bin/activate
    

    On Windows, activate the virtual environment with .venv\Scripts\activate instead.

  3. In the flask-quickstart folder, create a file named app.py with the following contents:

    from pathlib import Path
    
    from flask import Flask, redirect, render_template_string, request
    
    app = Flask(__name__)
    PORT = 3000
    TARGET_FILE = Path(__file__).parent / 'note.txt'
    
    # Ensure the file exists so we don't crash
    if not TARGET_FILE.exists():
        TARGET_FILE.write_text('Hello! Edit this text.')
    
    # Simple HTML UI
    PAGE = '''
    <!DOCTYPE html>
    <html>
    <head>
        <title>Text Editor</title>
        <style>
            body { font-family: sans-serif; margin: 40px; line-height: 1.6; }
            textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; }
            button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
            button:hover { background: #0056b3; }
        </style>
    </head>
    <body>
        <h1>Edit: {{ filename }}</h1>
        <form method="POST" action="/save">
            <textarea name="content">{{ content }}</textarea>
            <br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>
    '''
    
    
    @app.get('/')
    def home():
        return render_template_string(PAGE, filename=TARGET_FILE.name, content=TARGET_FILE.read_text())
    
    
    @app.post('/save')
    def save():
        TARGET_FILE.write_text(request.form['content'])
        return redirect('/')  # Refresh the page to show updated content
    
    
    if __name__ == '__main__':
        app.run(port=PORT)
  4. Install dependencies:

    $ pip install Flask==3.1.3
    
  5. Run the app:

    $ python app.py
    
  6. Open the app at http://localhost:3000.

  7. Replace the text area text with "Hello Flask", then click the Save Changes button.

  8. In a file browser or terminal, look in the flask-quickstart folder. You should see a new file named note.txt, with text content "Hello Flask".

  9. Congratulations, you have a working Flask app that lets you edit a local text file through your web browser. Press Ctrl+C on your keyboard to stop the Flask server.

Install and Run FusionAuth#

Before we can add authentication to our Flask app, we need a local FusionAuth instance:

  1. Open your container management tool (listed in the prerequisites above).

  2. From the flask-quickstart folder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:

    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    
  3. Navigate into the cloned directory:

    $ cd fusionauth-quickstart-app
    
  4. To start a local instance of FusionAuth, run the following command (omit the -d flag to see all Docker logs):

    $ docker compose up -d
    
  5. Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.

  6. Open http://localhost:9011/admin to access the FusionAuth Admin UI.

  7. Log in with these credentials:

    • username: admin@example.com
    • password: password
  8. Navigate to Applications -> QuickStart App -> Edit -> OAuth . On this page, you can find your client ID, your client secret, and specify redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Flask app with FusionAuth.

  9. Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Flask app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.

Add FusionAuth to the Flask App#

Now that you have a working instance of FusionAuth and a working Flask app, let's use FusionAuth to add login to your Flask app:

  1. Navigate out of the fusionauth-quickstart-app folder, back to the flask-quickstart folder that contains app.py and note.txt:

    $ cd ..
    
  2. Create a file named .env with the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):

    FUSIONAUTH_CLIENT_ID=f0510a74-da7a-4101-a474-05e7f1d5ba7e
    FUSIONAUTH_CLIENT_SECRET=super-secret-secret-that-should-be-regenerated-for-production
    FUSIONAUTH_CALLBACK_URL=http://localhost:3000/oauth-callback
    SESSION_SECRET=a_very_long_random_string
  3. Install the dependencies we'll need to authenticate with FusionAuth:

    $ pip install Authlib==1.9.5 requests==2.34.2 python-dotenv==1.2.4
    

    Most importantly, we're adding Authlib, which handles communication with our FusionAuth instance (using Requests to make HTTP calls), and python-dotenv, which handles reading our configuration from the .env file we just created.

  4. Replace the contents of app.py with the following code:

    import os
    from functools import wraps
    from pathlib import Path
    from urllib.parse import urlencode
    
    from flask import Flask, redirect, render_template_string, request, session
    
    # auth dependencies
    from authlib.integrations.flask_client import OAuth
    from dotenv import load_dotenv
    
    app = Flask(__name__)
    PORT = 3000
    TARGET_FILE = Path(__file__).parent / 'note.txt'
    
    # read configuration from .env file
    load_dotenv()
    FUSIONAUTH_URL = 'http://localhost:9011'
    CLIENT_ID = os.environ['FUSIONAUTH_CLIENT_ID']
    CLIENT_SECRET = os.environ['FUSIONAUTH_CLIENT_SECRET']
    CALLBACK_URL = os.environ['FUSIONAUTH_CALLBACK_URL']
    app.secret_key = os.environ['SESSION_SECRET']
    
    # tell authlib how to talk to fusionauth
    oauth = OAuth(app)
    oauth.register(
        'fusionauth',
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        server_metadata_url=f'{FUSIONAUTH_URL}/.well-known/openid-configuration',
        client_kwargs={'scope': 'openid', 'code_challenge_method': 'S256'},
    )
    
    
    # require authentication to access
    def login_required(view):
        @wraps(view)
        def wrapped(*args, **kwargs):
            if 'user' not in session:
                return redirect('/login')
            return view(*args, **kwargs)
        return wrapped
    
    
    # Ensure the file exists so we don't crash
    if not TARGET_FILE.exists():
        TARGET_FILE.write_text('Hello! Edit this text.')
    
    # Simple HTML UI
    PAGE = '''
    <!DOCTYPE html>
    <html>
    <head>
        <title>Text Editor</title>
        <style>
            body { font-family: sans-serif; margin: 40px; line-height: 1.6; }
            textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; }
            button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
            button:hover { background: #0056b3; }
            .logout-btn { background: #dc3545; color: white; padding: 8px 15px;
                          text-decoration: none; border-radius: 4px; float: right; }
        </style>
    </head>
    <body>
        <h1>Edit: {{ filename }}</h1>
        <form method="POST" action="/save">
            <textarea name="content">{{ content }}</textarea>
            <br>
            <button type="submit">Save Changes</button>
            <a href="/logout" class="logout-btn">Logout</a>
        </form>
    </body>
    </html>
    '''
    
    
    # --- Routes ---
    @app.get('/login')
    def login():
        return oauth.fusionauth.authorize_redirect(CALLBACK_URL)
    
    
    @app.get('/oauth-callback')
    def oauth_callback():
        token = oauth.fusionauth.authorize_access_token()
        # remember the user in the session cookie
        session['user'] = {'id': token['userinfo']['sub']}
        return redirect('/')
    
    
    @app.get('/logout')
    def logout():
        # Clear the local Flask session
        session.clear()
    
        # Redirect to FusionAuth to clear the SSO session
        # This ensures the user is actually logged out of the identity provider
        return redirect(f'{FUSIONAUTH_URL}/oauth2/logout?' + urlencode({'client_id': CLIENT_ID}))
    
    
    @app.get('/')
    @login_required
    def home():
        return render_template_string(PAGE, filename=TARGET_FILE.name, content=TARGET_FILE.read_text())
    
    
    @app.post('/save')
    @login_required
    def save():
        TARGET_FILE.write_text(request.form['content'])
        return redirect('/')  # Refresh the page to show updated content
    
    
    if __name__ == '__main__':
        app.run(port=PORT)

    The new code connects the app to FusionAuth:

    • load_dotenv() reads the configuration from the .env file.
    • oauth.register tells Authlib how to talk to FusionAuth. It uses the client Id, client secret, and PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges., and finds the login and token endpoints in the OpenID Connect discovery document at /.well-known/openid-configuration. With PKCE, Authlib sends a code verifier when it exchanges the authorization code for tokens, so a stolen authorization code is useless on its own.
    • The login_required decorator sends users who aren't logged in to /login.
    • The /login route calls authorize_redirect, which sends the user to the FusionAuth login page.
    • The /oauth-callback route calls authorize_access_token, which exchanges the authorization code from FusionAuth for tokens and validates the ID tokenA JSON Web Token that contains information about the authenticated user.. The app then stores the user's Id in the Flask session cookie.
    • The /logout route clears the Flask session, then sends the user to FusionAuth's /oauth2/logout endpoint so the FusionAuth session ends too.
  5. That's it! Your Flask app should now use FusionAuth login. Run the app:

    $ python app.py
    
  6. Open the app at http://localhost:3000.

  7. Log in with the following credentials:

    • username: richard@example.com
    • password: password
  8. Edit the text file from the safety of an authenticated Flask app.

  9. Click Logout. FusionAuth ends your session and sends you back to the login page.

Add Independent Notes for Each User#

To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:

  1. Open the FusionAuth Admin UI at http://localhost:9011/admin.

  2. Log in with the following credentials:

    • username: admin@example.com
    • password: password
  3. Navigate to Applications -> QuickStart App -> Edit -> Registration .

    • Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
    • In the Registration field list, turn on the Enabled and Required switches for the following rows:
      • Birthdate
      • First name
      • Last name
  4. Click the Save button in the top right of the page to save your changes to self-service registration.

  5. Navigate to Users -> Richard Hendricks -> Manage .

  6. In the Source tab, look for the firstName and lastName fields. That's what we'll use to personalize the UI for each user. We'll use the user's id field to generate a unique name for each user's note.

  7. Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Flask app.

  8. Replace the contents of app.py with the following code, which requests the profile and email scopes, reads the user's name (first and last) and Id from the ID token, and stores each user's note in a separate file:

    import os
    from functools import wraps
    from pathlib import Path
    from urllib.parse import urlencode
    
    from flask import Flask, redirect, render_template_string, request, session
    
    # auth dependencies
    from authlib.integrations.flask_client import OAuth
    from dotenv import load_dotenv
    
    app = Flask(__name__)
    PORT = 3000
    
    # set up a directory for multi-user files
    DATA_DIR = Path(__file__).parent / 'user_data'
    DATA_DIR.mkdir(exist_ok=True)
    
    # read configuration from .env file
    load_dotenv()
    FUSIONAUTH_URL = 'http://localhost:9011'
    CLIENT_ID = os.environ['FUSIONAUTH_CLIENT_ID']
    CLIENT_SECRET = os.environ['FUSIONAUTH_CLIENT_SECRET']
    CALLBACK_URL = os.environ['FUSIONAUTH_CALLBACK_URL']
    app.secret_key = os.environ['SESSION_SECRET']
    
    # tell authlib how to talk to fusionauth
    oauth = OAuth(app)
    oauth.register(
        'fusionauth',
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        server_metadata_url=f'{FUSIONAUTH_URL}/.well-known/openid-configuration',
        client_kwargs={'scope': 'openid profile email', 'code_challenge_method': 'S256'},
    )
    
    
    # require authentication to access
    def login_required(view):
        @wraps(view)
        def wrapped(*args, **kwargs):
            if 'user' not in session:
                return redirect('/login')
            return view(*args, **kwargs)
        return wrapped
    
    
    # helper to get specific user file
    def get_user_file(user_id):
        return DATA_DIR / f'note-{user_id}.txt'
    
    
    # Simple HTML UI
    PAGE = '''
    <!DOCTYPE html>
    <html>
    <head>
        <title>Text Editor</title>
        <style>
            body { font-family: sans-serif; margin: 40px; line-height: 1.6; }
            textarea { width: 100%; height: 300px; padding: 10px; margin-bottom: 10px; }
            button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
            button:hover { background: #0056b3; }
            .logout-btn { background: #dc3545; color: white; padding: 8px 15px;
                          text-decoration: none; border-radius: 4px; float: right; }
        </style>
    </head>
    <body>
        <a href="/logout" class="logout-btn">Logout</a>
        <p style="float: right; margin-right: 20px;">Welcome, {{ name }}</p>
        <h1>Personal Note Editor</h1>
        <form method="POST" action="/save">
            <textarea name="content">{{ content }}</textarea>
            <br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>
    '''
    
    
    # --- routes ---
    @app.get('/login')
    def login():
        return oauth.fusionauth.authorize_redirect(CALLBACK_URL)
    
    
    @app.get('/oauth-callback')
    def oauth_callback():
        token = oauth.fusionauth.authorize_access_token()
    
        # authlib validates the ID token and decodes its claims into userinfo
        userinfo = token['userinfo']
        full_name = f"{userinfo.get('given_name', '')} {userinfo.get('family_name', '')}".strip()
    
        session['user'] = {
            'id': userinfo['sub'],
            'email': userinfo.get('email'),
            'name': full_name or userinfo.get('email') or 'User',
        }
        return redirect('/')
    
    
    @app.get('/logout')
    def logout():
        # Clear the local Flask session
        session.clear()
    
        # Redirect to FusionAuth to clear the SSO session
        return redirect(f'{FUSIONAUTH_URL}/oauth2/logout?' + urlencode({
            'client_id': CLIENT_ID,
            'post_logout_redirect_uri': 'http://localhost:3000/login',
        }))
    
    
    @app.get('/')
    @login_required
    def home():
        user = session['user']
        target_file = get_user_file(user['id'])
    
        # Ensure the file exists so we don't crash
        if not target_file.exists():
            target_file.write_text(f"Hello {user['name']}!")
    
        return render_template_string(PAGE, name=user['name'], content=target_file.read_text())
    
    
    @app.post('/save')
    @login_required
    def save():
        get_user_file(session['user']['id']).write_text(request.form['content'])
        return redirect('/')  # Refresh the page to show updated content
    
    
    if __name__ == '__main__':
        app.run(port=PORT)

    Authlib validates the ID token and decodes its claims into token['userinfo'], so we don't need a separate JWT library. The logout route also passes a post_logout_redirect_uri, which sends the user back to the login page after FusionAuth ends their session.

  9. Restart the app (press Ctrl+C, then run python app.py again) and open it at http://localhost:3000.

  10. Log in with the following credentials:

    • username: richard@example.com
    • password: password
  11. In a separate private/incognito window, open the app at http://localhost:3000.

  12. Click Create an account and create an account using your personal email address, name, and birthdate.

  13. Enjoy using your unique user note! You should see your name at the top of the page, and in the default note text.

Your Flask app now provides unique notes for each user. Each user can independently edit and save their note. To see all of the notes, look for note-<id>.txt files in the user_data directory. To identify which note corresponds to which user, compare the id in the file name with the id field in the user's Source tab.

Summary#

In this QuickStart, FusionAuth handled login for your Flask app:

  • Authlib sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
  • The login_required decorator kept logged-out users away from the notes page.
  • The ID token gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
  • FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.

Next Steps#

This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.

FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.