API References of Flask OAuth 2.0 Server

This part of the documentation covers the interface of Flask OAuth 2.0 Server.

class authlib.integrations.flask_oauth2.AuthorizationServer(app=None, query_client=None, save_token=None)

Flask implementation of authlib.oauth2.rfc6749.AuthorizationServer. Initialize it with query_client, save_token methods and Flask app instance:

def query_client(client_id):
    return Client.query.filter_by(client_id=client_id).first()

def save_token(token, request):
    if request.user:
        user_id = request.user.id
    else:
        user_id = None
    client = request.client
    tok = Token(
        client_id=client.client_id,
        user_id=user.id,
        **token
    )
    db.session.add(tok)
    db.session.commit()

server = AuthorizationServer(app, query_client, save_token)
# or initialize lazily
server = AuthorizationServer()
server.init_app(app, query_client, save_token)
create_authorization_response(request=None, grant_user=None)

Validate authorization request and create authorization response.

Parameters:
  • request – HTTP request instance.

  • grant_user – if granted, it is resource owner. If denied, it is None.

Returns:

Response

create_bearer_token_generator(config)

Create a generator function for generating token value. This method will create a Bearer Token generator with authlib.oauth2.rfc6750.BearerToken.

Configurable settings:

  1. OAUTH2_ACCESS_TOKEN_GENERATOR: Boolean or import string, default is True.

  2. OAUTH2_REFRESH_TOKEN_GENERATOR: Boolean or import string, default is False.

  3. OAUTH2_TOKEN_EXPIRES_IN: Dict or import string, default is None.

By default, it will not generate refresh_token, which can be turn on by configure OAUTH2_REFRESH_TOKEN_GENERATOR.

Here are some examples of the token generator:

OAUTH2_ACCESS_TOKEN_GENERATOR = 'your_project.generators.gen_token'

# and in module `your_project.generators`, you can define:

def gen_token(client, grant_type, user, scope):
    # generate token according to these parameters
    token = create_random_token()
    return f'{client.id}-{user.id}-{token}'

Here is an example of OAUTH2_TOKEN_EXPIRES_IN:

OAUTH2_TOKEN_EXPIRES_IN = {
    'authorization_code': 864000,
    'urn:ietf:params:oauth:grant-type:jwt-bearer': 3600,
}
create_endpoint_response(name, request=None)

Validate endpoint request and create endpoint response.

Parameters:
  • name – Endpoint name

  • request – HTTP request instance.

Returns:

Response

create_token_response(request=None)

Validate token request and create token response.

Parameters:

request – HTTP request instance

Validate current HTTP request for authorization page. This page is designed for resource owner to grant or deny the authorization.

register_endpoint(endpoint)

Add extra endpoint to authorization server. e.g. RevocationEndpoint:

authorization_server.register_endpoint(RevocationEndpoint)
Parameters:

endpoint_cls – A endpoint class or instance.

register_grant(grant_cls, extensions=None)

Register a grant class into the endpoint registry. Developers can implement the grants in authlib.oauth2.rfc6749.grants and register with this method:

class AuthorizationCodeGrant(grants.AuthorizationCodeGrant):
    def authenticate_user(self, credential):
        # ...

authorization_server.register_grant(AuthorizationCodeGrant)
Parameters:
  • grant_cls – a grant class.

  • extensions – extensions for the grant class.

class authlib.integrations.flask_oauth2.ResourceProtector

A protecting method for resource servers. Creating a require_oauth decorator easily with ResourceProtector:

from authlib.integrations.flask_oauth2 import ResourceProtector

require_oauth = ResourceProtector()

# add bearer token validator
from authlib.oauth2.rfc6750 import BearerTokenValidator
from project.models import Token

class MyBearerTokenValidator(BearerTokenValidator):
    def authenticate_token(self, token_string):
        return Token.query.filter_by(access_token=token_string).first()

require_oauth.register_token_validator(MyBearerTokenValidator())

# protect resource with require_oauth

@app.route('/user')
@require_oauth(['profile'])
def user_profile():
    user = User.get(current_token.user_id)
    return jsonify(user.to_dict())
raise_error_response(error)

Raise HTTPException for OAuth2Error. Developers can re-implement this method to customize the error response.

Parameters:

error – OAuth2Error

Raise:

HTTPException

acquire_token(scopes=None, **kwargs)

A method to acquire current valid token with the given scope.

Parameters:

scopes – a list of scope values

Returns:

token object

acquire(scopes=None)

The with statement of require_oauth. Instead of using a decorator, you can use a with statement instead:

@app.route('/api/user')
def user_api():
    with require_oauth.acquire('profile') as token:
        user = User.get(token.user_id)
        return jsonify(user.to_dict())
authlib.integrations.flask_oauth2.current_token

Routes protected by ResourceProtector can access current token with this variable:

from authlib.integrations.flask_oauth2 import current_token

@require_oauth()
@app.route('/user_id')
def user_id():
    # current token instance of the OAuth Token model
    return current_token.user_id
authlib.integrations.flask_oauth2.client_authenticated

Signal when client is authenticated

authlib.integrations.flask_oauth2.token_revoked

Signal when token is revoked

authlib.integrations.flask_oauth2.token_authenticated

Signal when token is authenticated

SQLAlchemy Helper Functions

Warning

We will drop sqla_oauth2 module in version 1.0.

authlib.integrations.sqla_oauth2.create_query_client_func(session, client_model)

Create an query_client function that can be used in authorization server.

Parameters:
  • session – SQLAlchemy session

  • client_model – Client model class

authlib.integrations.sqla_oauth2.create_save_token_func(session, token_model)

Create an save_token function that can be used in authorization server.

Parameters:
  • session – SQLAlchemy session

  • token_model – Token model class

authlib.integrations.sqla_oauth2.create_query_token_func(session, token_model)

Create an query_token function for revocation, introspection token endpoints.

Parameters:
  • session – SQLAlchemy session

  • token_model – Token model class

authlib.integrations.sqla_oauth2.create_revocation_endpoint(session, token_model)

Create a revocation endpoint class with SQLAlchemy session and token model.

Parameters:
  • session – SQLAlchemy session

  • token_model – Token model class

authlib.integrations.sqla_oauth2.create_bearer_token_validator(session, token_model)

Create an bearer token validator class with SQLAlchemy session and token model.

Parameters:
  • session – SQLAlchemy session

  • token_model – Token model class