All Projects → authlib → Example Oauth2 Server

authlib / Example Oauth2 Server

Example for OAuth 2 Server for Authlib.

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Example Oauth2 Server

Doorkeeper
Doorkeeper is an OAuth 2 provider for Ruby on Rails / Grape.
Stars: ✭ 4,917 (+885.37%)
Mutual labels:  oauth2, oauth2-server, oauth2-provider
Authlib
The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.
Stars: ✭ 2,854 (+471.94%)
Mutual labels:  oauth2, oauth2-server, oauth2-provider
Light Oauth2
A fast, light and cloud native OAuth 2.0 authorization microservices based on light-4j
Stars: ✭ 247 (-50.5%)
Mutual labels:  oauth2, oauth2-server, oauth2-provider
Oauth2 Server
OAuth2 Server Library
Stars: ✭ 42 (-91.58%)
Mutual labels:  oauth2, oauth2-server, oauth2-provider
Flask Oauthlib
YOU SHOULD USE https://github.com/lepture/authlib
Stars: ✭ 1,429 (+186.37%)
Mutual labels:  oauth2, oauth2-server, oauth2-provider
Doorkeeper Provider App
An example OAuth 2 provider application using the Doorkeeper gem, Rails and Devise
Stars: ✭ 146 (-70.74%)
Mutual labels:  oauth2, oauth2-server, oauth2-provider
Hydra
OpenID Certified™ OpenID Connect and OAuth Provider written in Go - cloud native, security-first, open source API security for your infrastructure. SDKs for any language. Compatible with MITREid.
Stars: ✭ 11,884 (+2281.56%)
Mutual labels:  oauth2, oauth2-server, oauth2-provider
Oauth2
OAuth 2.0 server library for the Go programming language.
Stars: ✭ 2,173 (+335.47%)
Mutual labels:  oauth2, oauth2-server, oauth2-provider
Express Gateway
A microservices API Gateway built on top of Express.js
Stars: ✭ 2,583 (+417.64%)
Mutual labels:  oauth2, oauth2-server
oauth2-server
A spec compliant, secure by default PHP OAuth 2.0 Server
Stars: ✭ 6,128 (+1128.06%)
Mutual labels:  oauth2, oauth2-server
jpsite-security-oauth2-open
微服务开放API授权平台
Stars: ✭ 21 (-95.79%)
Mutual labels:  oauth2, oauth2-server
Perfect-Authentication
OAuth2 Implementations with Facebook, Google, LinkedIn, Slack, SalesForce and GitHub providers.
Stars: ✭ 14 (-97.19%)
Mutual labels:  oauth2, oauth2-provider
Egg Oauth2 Server
🌟 OAuth2 server plugin for egg.js based on node-oauth2-server
Stars: ✭ 174 (-65.13%)
Mutual labels:  oauth2, oauth2-server
genkan
🔑 The future of Kitsu's Authentication
Stars: ✭ 13 (-97.39%)
Mutual labels:  oauth2, oauth2-server
phoenix oauth2 provider
Get an OAuth 2 provider running in your phoenix with controllers, views and models in just two minutes
Stars: ✭ 72 (-85.57%)
Mutual labels:  oauth2-provider, oauth2-server
Oauth2 Server
spring boot (springboot 2+) oauth2 server sso 单点登录 认证中心 JWT,独立部署,用户管理 客户端管理
Stars: ✭ 363 (-27.25%)
Mutual labels:  oauth2-server, oauth2-provider
Oauth2 Family Barrel
OAuth2全家桶项目。本项目演示了如何使用spring-boot、spring-security以及spring-security-oauth快速构建OAuth2服务框架体系。
Stars: ✭ 188 (-62.32%)
Mutual labels:  oauth2, oauth2-provider
SimpleOAuth
Simple OAuth 2.0 for Android
Stars: ✭ 15 (-96.99%)
Mutual labels:  oauth2, oauth2-provider
Hiauth
HiAuth是一个开源的基于Oauth2协议的认证、授权系统。
Stars: ✭ 273 (-45.29%)
Mutual labels:  oauth2, oauth2-server
Oauth2 Google
Google Provider for the OAuth 2.0 Client
Stars: ✭ 268 (-46.29%)
Mutual labels:  oauth2, oauth2-provider

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.

Sponsors

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 auth0.com/overview.

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)
$ export AUTHLIB_INSECURE_TRANSPORT=1

Create Database and run the development server:

$ flask run

Now, you can open your browser with http://127.0.0.1:5000/, 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 http://127.0.0.1:5000/oauth/token -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}" http://127.0.0.1:5000/api/me

Authorization code flow example

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

$ open http://127.0.0.1:5000/oauth/authorize?response_type=code&client_id=${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 http://127.0.0.1:5000/oauth/token -F grant_type=authorization_code -F scope=profile -F code=${code}

Now you can access /api/me:

$ curl -H "Authorization: Bearer ${access_token}" http://127.0.0.1:5000/api/me

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.

Preparation

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:

app.py         --- FLASK_APP
website/
  app.py       --- Flask App Factory
  __init__.py  --- module initialization (empty)
  models.py    --- SQLAlchemy Models
  oauth2.py    --- OAuth 2.0 Provider Configuration
  routes.py    --- Routes views
  templates/

Installation

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

Flask
Flask-SQLAlchemy
Authlib

Hello World!

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

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

@bp.route('/')
def home():
    return 'Hello World!'
# website/app.py
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):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)
    setup_app(app)
    return app

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

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

Create an empty __init__.py file in the website folder.

The "Hello World!" example should run properly:

$ FLASK_APP=app.py 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/models.py. 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/models.py.

Once you've created your own website/models.py (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/app.py.

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

def setup_app(app):
    # Create tables if they do not exist already
    @app.before_first_request
    def create_tables():
        db.create_all()

    db.init_app(app)
    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/oauth2.py. 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/oauth2.py.

Once you've created your own website/oauth2.py, 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/app.py.

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
    @app.before_first_request
    def create_tables():
        db.create_all()

    db.init_app(app)
    config_oauth(app)
    app.register_blueprint(bp, url_prefix='')

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

@require_oauth

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)
require_oauth.register_token_validator(bearer_cls())

Check the full implementation in website/oauth2.py.

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/routes.py. 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.

Finish

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

Read more information on https://docs.authlib.org/.

License

Same license with Authlib.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].