Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork287
Example for OAuth 2 Server for Authlib.
authlib/example-oauth2-server
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This is an example of OAuth 2.0 server inAuthlib.If you are looking for old Flask-OAuthlib implementation, check theflask-oauthlib branch.
- Documentation:https://docs.authlib.org/en/latest/flask/2/
- Authlib Repo:https://github.com/lepture/authlib
![]() | If you want to quickly add secure token-based authentication to Python projects, feel free to check Auth0's Python SDK and free plan atauth0.com/overview. |
This is a ready to run example, let's take a quick experience at first. Torun 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 withhttp://127.0.0.1:5000/, login with anyname you want.
Before testing, we need to create a client:
Get yourclient_id andclient_secret for testing. In this example, wehave enabledpassword 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=profileBecause this is an example, every user's password isvalid. Now you can access/api/me:
$ curl -H"Authorization: Bearer${access_token}" http://127.0.0.1:5000/api/meTo 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/meFor now, you can read the source in example or follow the long boring tutorial below.
IMPORTANT: To test implicit grant, you need totoken_endpoint_auth_method tonone.
Assume this example doesn't exist at all. Let's write an OAuth 2.0 serverfrom scratch step by step.
Here is our Flask website structure:
app.py --- FLASK_APPwebsite/ 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/Create a virtualenv and install all the requirements. You can also put thedependencies intorequirements.txt:
FlaskFlask-SQLAlchemyAuthlibCreate a home route view to say "Hello World!". It is used to test if thingsworking well.
# website/routes.pyfromflaskimportBlueprintbp=Blueprint(__name__,'home')@bp.route('/')defhome():return'Hello World!'
# website/app.pyfromflaskimportFlaskfrom .routesimportbpdefcreate_app(config=None):app=Flask(__name__)# load app sepcified configurationifconfigisnotNone:ifisinstance(config,dict):app.config.update(config)elifconfig.endswith('.py'):app.config.from_pyfile(config)setup_app(app)returnappdefsetup_app(app):app.register_blueprint(bp,url_prefix='')
# app.pyfromwebsite.appimportcreate_appapp=create_app({'SECRET_KEY':'secret',})
Create an empty__init__.py file in thewebsite folder.
The "Hello World!" example should run properly:
$ FLASK_APP=app.py flask runWe will use SQLAlchemy and SQLite for our models. You can also use otherdatabases and other ORM engines. Authlib has some built-in SQLAlchemy mixinswhich will make it easier for creating models.
Let's create the models inwebsite/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=codeflow - OAuth2Token: save the
access_tokenin this model.
Check how to define these models inwebsite/models.py.
Once you've created your ownwebsite/models.py (or copied our version), you'll need to import the database objectdb. Add the linefrom .models import db just afterfrom flask import Flask in your scratch-built version ofwebsite/app.py.
To initialize the database upon startup, if no tables exist, you'll add a few lines to thesetup_app() function inwebsite/app.py so that it now looks like:
defsetup_app(app):# Create tables if they do not exist already@app.before_first_requestdefcreate_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.
The source code is inwebsite/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 doanything on Implicit and Client Credentials grants, but there are missingmethods to be implemented in other grants. Check out the source code inwebsite/oauth2.py.
Once you've created your ownwebsite/oauth2.py, import the oauth2 config object from the oauth2 module. Add the linefrom .oauth2 import config_oauth just after the import you added above in your scratch-built version ofwebsite/app.py.
To initialize the oauth object, addconfig_oauth(app) to thesetup_app() function, just before the line that starts withapp.register_blueprint so it looks like:
defsetup_app(app):# Create tables if they do not exist already@app.before_first_requestdefcreate_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.
Authlib has provided aResourceProtector for you to create the decorator@require_oauth, which can be easily implemented:
fromauthlib.flask.oauth2importResourceProtectorrequire_oauth=ResourceProtector()
For now, only Bearer Token is supported. Let's add bearer token validator tothis ResourceProtector:
fromauthlib.flask.oauth2.sqlaimportcreate_bearer_token_validator# helper function: create_bearer_token_validatorbearer_cls=create_bearer_token_validator(db.session,OAuth2Token)require_oauth.register_token_validator(bearer_cls())
Check the full implementation inwebsite/oauth2.py.
For OAuth server itself, we only need to implement routes for authentication,and issuing tokens. Since we have added token revocation feature, we need aroute for revoking too.
Checkout these routes inwebsite/routes.py. Their path begin with/oauth/.
But that is not enough. In this demo, you will need to have some web pages tocreate 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 onhttps://docs.authlib.org/.
Same license withAuthlib.
About
Example for OAuth 2 Server for Authlib.
Topics
Resources
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.

