Skip to content


Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?


Failed to load latest commit information.

How to create an OAuth 2.0 Provider

This is an example of OAuth 2.0 server in Authlib. If you are looking for old Flask-OAuthlib implementation, check the flask-oauthlib branch.


If you want to quickly add secure token-based authentication to Python projects, feel free to check Auth0's Python SDK and free plan at

Take a quick look

This is a ready to run example, let's take a quick experience at first. To run the example, we need to install all the dependencies:

$ pip install -r requirements.txt

Set Flask and Authlib environment variables:

# disable check https (DO NOT SET THIS IN PRODUCTION)

Create Database and run the development server:

$ flask run

Now, you can open your browser with, login with any name you want.

Before testing, we need to create a client:

create a client

Password flow example

Get your client_id and client_secret for testing. In this example, we have enabled password grant types, let's try:

$ curl -u ${client_id}:${client_secret} -XPOST -F grant_type=password -F username=${username} -F password=valid -F scope=profile

Because this is an example, every user's password is valid. Now you can access /api/me:

$ curl -H "Authorization: Bearer ${access_token}"

Authorization code flow example

To test the authorization code flow, you can just open this URL in your browser.

$ open${client_id}&scope=profile

After granting the authorization, you should be redirected to ${redirect_uri}/?code=${code}

Then your app can send the code to the authorization server to get an access token:

$ curl -u ${client_id}:${client_secret} -XPOST -F grant_type=authorization_code -F scope=profile -F code=${code}

Now you can access /api/me:

$ curl -H "Authorization: Bearer ${access_token}"

For now, you can read the source in example or follow the long boring tutorial below.

IMPORTANT: To test implicit grant, you need to token_endpoint_auth_method to none.


Assume this example doesn't exist at all. Let's write an OAuth 2.0 server from scratch step by step.

Create folder structure

Here is our Flask website structure:         --- FLASK_APP
website/       --- Flask App Factory  --- module initialization (empty)    --- SQLAlchemy Models    --- OAuth 2.0 Provider Configuration    --- Routes views


Create a virtualenv and install all the requirements. You can also put the dependencies into requirements.txt:


Hello World!

Create a home route view to say "Hello World!". It is used to test if things working well.

# website/
from flask import Blueprint
bp = Blueprint(__name__, 'home')

def home():
    return 'Hello World!'
# website/
from flask import Flask
from .routes import bp

def create_app(config=None):
    app = Flask(__name__)
    # load app sepcified configuration
    if config is not None:
        if isinstance(config, dict):
        elif config.endswith('.py'):
    return app

def setup_app(app):
    app.register_blueprint(bp, url_prefix='')
from import create_app

app = create_app({
    'SECRET_KEY': 'secret',

Create an empty file in the website folder.

The "Hello World!" example should run properly:

$ flask run

Define Models

We will use SQLAlchemy and SQLite for our models. You can also use other databases and other ORM engines. Authlib has some built-in SQLAlchemy mixins which will make it easier for creating models.

Let's create the models in website/ We need four models, which are

  • User: you need a user to test and create your application
  • OAuth2Client: the oauth client model
  • OAuth2AuthorizationCode: for grant_type=code flow
  • OAuth2Token: save the access_token in this model.

Check how to define these models in website/

Once you've created your own website/ (or copied our version), you'll need to import the database object db. Add the line from .models import db just after from flask import Flask in your scratch-built version of website/

To initialize the database upon startup, if no tables exist, you'll add a few lines to the setup_app() function in website/ so that it now looks like:

def setup_app(app):
    # Create tables if they do not exist already
    def create_tables():

    app.register_blueprint(bp, url_prefix='')

You can try running the app again as above to make sure it works.

Implement Grants

The source code is in website/ There are four standard grant types:

  • Authorization Code Grant
  • Implicit Grant
  • Client Credentials Grant
  • Resource Owner Password Credentials Grant

And Refresh Token is implemented as a Grant in Authlib. You don't have to do anything on Implicit and Client Credentials grants, but there are missing methods to be implemented in other grants. Check out the source code in website/

Once you've created your own website/, import the oauth2 config object from the oauth2 module. Add the line from .oauth2 import config_oauth just after the import you added above in your scratch-built version of website/

To initialize the oauth object, add config_oauth(app) to the setup_app() function, just before the line that starts with app.register_blueprint so it looks like:

def setup_app(app):
    # Create tables if they do not exist already
    def create_tables():

    app.register_blueprint(bp, url_prefix='')

You can try running the app again as above to make sure it still works.


Authlib has provided a ResourceProtector for you to create the decorator @require_oauth, which can be easily implemented:

from authlib.flask.oauth2 import ResourceProtector

require_oauth = ResourceProtector()

For now, only Bearer Token is supported. Let's add bearer token validator to this ResourceProtector:

from authlib.flask.oauth2.sqla import create_bearer_token_validator

# helper function: create_bearer_token_validator
bearer_cls = create_bearer_token_validator(db.session, OAuth2Token)

Check the full implementation in website/

OAuth Routes

For OAuth server itself, we only need to implement routes for authentication, and issuing tokens. Since we have added token revocation feature, we need a route for revoking too.

Checkout these routes in website/ Their path begin with /oauth/.

Other Routes

But that is not enough. In this demo, you will need to have some web pages to create and manage your OAuth clients. Check that /create_client route.

And we have an API route for testing. Check the code of /api/me.


Here you go. You've got an OAuth 2.0 server.

Read more information on


Same license with Authlib.