Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • Start Building
    • 5-Minute Guide
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Validate JWT in your application server
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
  • How-To Guides
    • Authenticate
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Add authentication to any web page
      • Enable Two-Factor Authentication (2FA)
      • Reauthentication
      • Passwordless Login for Apple App Store Review
      • Change Forgot/Reset Password settings
      • Adjust Phone Number Validation
      • Set Password Expiry
      • Use the OAuth 2.0 State Parameter
      • Setup local development environment for Cookie-based authentication
      • Use Social/Enterprise Login Providers Without AuthUI
    • Single Sign-on
      • App2App Login
      • Pre-authenticated URLs
      • SSO between Mobile Apps / Websites
      • Force Authgear to Show Login Page
      • Single Sign-On with OIDC
      • Single Sign-On with SAML
        • Use Authgear as SAML Identity Provider for Salesforce
        • Use Authgear as SAML Identity Provider for Dropbox
        • SAML Attribute Mapping
    • Social Login / Enterprise Login Providers
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
    • Integrate
      • Add custom fields to a JWT Access Token
      • User Analytics by Google Tag Manager
      • Track User Before and After Signup
      • Custom domain
      • Custom Email Provider
      • Custom SMS Provider
        • Twilio
        • Webhook/Custom Script
      • Integrate Authgear with Firebase
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Only Allow Signups from Inside the Corporate Network using Hooks
    • Mobile Apps
      • Use SDK to make authorized API calls to backend
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Directly accessing Authgear Endpoint
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Design
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Languages and Localization
    • Custom Email and SMS Templates
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Authgear ONCE
    • What is Authgear ONCE
    • Install Authgear ONCE on a VM
    • Install Authgear ONCE on Vultr
    • Install Authgear ONCE on Amazon Web Services (AWS)
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • Admin API Examples
        • Using global node IDs
        • Retrieving users using Admin API
        • User Management Examples
          • Search for users
          • Update user's standard attributes
          • Update user's picture
          • Generate OTP code
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • UserInfo
        • Supported Scopes
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Glossary
    • Billing FAQ
    • Rate Limits
      • Account Lockout
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deploy on your Cloud
    • Running locally with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configurations
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Reference Architecture Diagrams
      • Google Cloud Reference Architecture
      • Azure Reference Architecture
      • AWS Reference Architecture
      • Throughput Scaling Reference
Powered by GitBook
On this page
  • Learning objectives
  • Prerequisites
  • Part 1: Configure Authgear
  • Part 2: Create a Flask application
  • Next steps

Was this helpful?

Edit on GitHub
Export as PDF
  1. Get Started
  2. Regular Web App

Python Flask App

Authentication for a Python web application

PreviousNext.jsNextJava Spring Boot

Last updated 2 months ago

Was this helpful?

This guide demonstrates how to add authentication with Authgear to a Python web application built with the framework using the OAuth library. The full source code for this sample project can be found on the .

Learning objectives

You will learn the following:

  • How to create an app on Authgear.

  • How to enable Email-based login.

  • Add sign-up and login features to the Flask app.

Prerequisites

Before you begin, you'll need the following:

  • A free Authgear account. if you don't have one already.

  • Make sure that 3.10 or above is installed on your machine.

  • Download and Install to manage project packages.

Part 1: Configure Authgear

To use Authgear services, you’ll need to have an application set up in the Authgear . This setup allows users in Authgear to sign in to the Flask application automatically once they are authenticated by Authgear.

Step 1: Configure an application

To set up the application, navigate to the and select Applications on the left-hand navigation bar. Use the interactive selector to create a new Authgear OIDC Client application or select an existing application that represents the project you want to integrate with.

Every application in Authgear is assigned an alphanumeric, unique client ID that your application code will use to call Authgear APIs through the Authlib client library in the Flask app. Record the generated Authgear Issuer Domain (for example, example-auth.authgear-apps.com), CLIENT ID, CLIENT SECRET from the output. You will use these values in Part 2 for the Flask app config.

Step 2: Configure Redirect URI

Step 3: Choose a Login method

After you create the Authgear app, you choose how users need to authenticate on the login page. From the Authentication tab, navigate to Login Methods, you can choose a login method from various options including, by email, mobile, or social, just using a username or the custom method you specify. For this demo, we choose the Email+Passwordless approach where our users are asked to register an account and log in by using their emails. They will receive a One-time password (OTP) to their emails and verify the code to use the app.

Part 2: Create a Flask application

Next, create a Flask application with a single page and routes for home, callback, login, and logout flows.

Step 1: Configure an .env file

Start with creating a requirements.txt file in your project directory:

flask>=2.0.3
python-dotenv>=0.19.2
authlib>=1.0
requests>=2.27.1

Run pip install -r requirements.txt from your command-line interface to make these dependencies available to the Python project.

Step 2: Setup the application

Create a server.py file in the project directory that contains application logic. Add the necessary libraries the application uses.

import json
from os import environ as env
from urllib.parse import quote_plus, urlencode

from authlib.integrations.flask_client import OAuth
from dotenv import find_dotenv, load_dotenv
from flask import Flask, redirect, render_template, session, url_for

Load the configuration .env file to use values such as AUTHGEAR_CLIENT_ID AUTHGEAR_CLIENT_SECRET, AUTHGEAR_DOMAIN and APP_SECRET_KEY in the app.

Configure Authlib to handle the application's authentication with Authgear based on OIDC:

oauth = OAuth(app)

oauth.register(
    "authgear",
    client_id=env.get("AUTHGEAR_CLIENT_ID"),
    client_secret=env.get("AUTHGEAR_CLIENT_SECRET"),
    client_kwargs={
        "scope": "openid offline_access",
    },
    server_metadata_url=f'https://{env.get("AUTHGEAR_DOMAIN")}/.well-known/openid-configuration',
)

Step 3: Setup the application routes

When visitors to the app visit the /login route, they'll be redirected to Authgear to begin the authentication flow.

@app.route("/login")
def login():
    return oauth.authgear.authorize_redirect(
        redirect_uri=url_for("callback", _external=True)
    )

Once users complete the login process using Authgear, they will be redirected back to the application's /callback route. This route ensures that the user's session is saved, so they won't need to log in again during subsequent visits.

@app.route("/callback", methods=["GET", "POST"])
def callback():
    token = oauth.authgear.authorize_access_token()
    session["user"] = token
    return redirect("/")

Refresh Token

Calling the authorize_access_token() method of the Flask Authlib package will include a refresh token in the token response, provided your Flask application has offline_access as one of the OAuth 2.0 scopes.

Authlib will also use the refresh token to obtain a new access token automatically when the current access token has expired.

Logout

The route /logout manages the user's logout process from the application. It clears the user's session within the app and momentarily redirects to Authgear's logout endpoint to guarantee a thorough session clearance. After this, users are navigated back to your home route (which we'll discuss shortly).

@app.route("/logout")
def logout():
    session.clear()
    return redirect(
        "https://"
        + env.get("AUTHGEAR_DOMAIN")
        + "/oauth2/end_session"
    )

The home route will either display the details of a logged-in user or provide an option for visitors to sign in.

@app.route("/")
def home():
    return render_template(
        "home.html",
        session=session.get("user"),
        pretty=json.dumps(session.get("user"), indent=4),
    )

Step 4: Add UI page

Create a new sub-directory in the project folder named templates, and create a file home.html.

<html>
  <head>
    <meta charset="utf-8" />
    <title>Authgear Flak Login Example</title>
  </head>
  <body>
    <div data-gb-custom-block data-tag="if">
    <h1>Welcome {{session.userinfo.name}}!</h1>
    <p><a href="/logout" id="qsLogoutBtn">Logout</a></p>
    <div><pre>{{pretty}}</pre></div>
    <div data-gb-custom-block data-tag="else"></div>
    <h1 id="profileDropDown">Welcome Guest</h1>
    <p><a href="/login" id="qsLoginBtn">Login</a></p>
    </div>
  </body>
</html>

Step 5: Run the application

Run the application from the project root directory:

python server.py

Next steps

An Authorized Redirect URI of your application is the URL that Authgear will redirect to after the user has authenticated in the Authgear to complete the authentication process. In our case, it will be a home page for our Flask and it will run at .

Set the following to the Authorized Redirect URIs field. If not set, users will not be returned to your application after they log in.

The application should now be accessible to open from a browser at .

There is so much more you can do with Authgear. Explore other means of login methods such as using in an email, , or . For the current application, you can also from the Authgear portal.

Flask
Authlib
GitHub repo
Sign up
Python
Pip
Dashboard
Authgear Portal UI
http://localhost:3000
http://localhost:3000
Magic links
social logins
WhatsApp OTP
add more users
http://localhost:3000/callback