API References of Flask OAuth 2.0 Server

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

class authlib.flask.oauth2.AuthorizationServer(app=None, query_client=None, save_token=None, **config)

Flask implementation of authlib.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.get_user_id()
    else:
        user_id = None
    client = request.client
    tok = Token(
        client_id=client.client_id,
        user_id=user.get_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 – OAuth2Request instance.
  • grant_user – if granted, it is resource owner. If denied, it is None.
Returns:

Response

create_bearer_token_generator(app)

Create a generator function for generating token value. This method will create a Bearer Token generator with authlib.specs.rfc6750.BearerToken. By default, it will not generate refresh_token, which can be turn on by configuration OAUTH2_REFRESH_TOKEN_GENERATOR=True.

create_endpoint_response(name, request=None)

Validate endpoint request and create endpoint response.

Parameters:
  • name – Endpoint name
  • request – OAuth2Request instance.
Returns:

Response

create_token_expires_in_generator(app)

Create a generator function for generating expires_in value. Developers can re-implement this method with a subclass if other means required. The default expires_in value is defined by grant_type, different grant_type has different value. It can be configured with:

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

Validate token request and create token response.

Parameters:request – OAuth2Request instance
register_endpoint(endpoint_cls)

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

authorization_server.register_endpoint(RevocationEndpoint)
Parameters:endpoint_cls – A token endpoint class
register_grant(grant_cls, extensions=None)

Register a grant class into the endpoint registry. Developers can implement the grants in authlib.specs.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.

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

@app.route('/authorize', methods=['GET'])
def authorize():
    try:
        grant = server.validate_consent_request(end_user=current_user)
        return render_template(
            'authorize.html',
            grant=grant,
            user=current_user
        )
    except OAuth2Error as error:
        return render_template(
            'error.html',
            error=error
        )
class authlib.flask.oauth2.ResourceProtector

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

from authlib.flask.oauth2 import ResourceProtector

require_oauth = ResourceProtector()

# add bearer token validator
from authlib.specs.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()

    def request_invalid(self, request):
        return False

    def token_revoked(self, token):
        return False

require_oauth.register_token_validator(MyBearerTokenValidator())

# protect resource with require_oauth

@app.route('/user')
@require_oauth('profile')
def user_profile():
    user = User.query.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(scope=None, operator='AND')

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

Parameters:
  • scope – string or list of scope values
  • operator – value of “AND” or “OR”
Returns:

token object

acquire(scope=None, operator='AND')

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.query.get(token.user_id)
        return jsonify(user.to_dict())
authlib.flask.oauth2.current_token

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

from authlib.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

Cache Helper Functions

authlib.flask.oauth2.cache.register_cache_authorization_code(cache, authorization_server, authenticate_user)

Use cache for authorization code grant endpoint.

Parameters:
  • cache – Cache instance.
  • authorization_server – AuthorizationServer instance.
  • authenticate_user – A function to authenticate user.

SQLAlchemy Helper Functions

authlib.flask.oauth2.sqla.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.flask.oauth2.sqla.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.flask.oauth2.sqla.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.flask.oauth2.sqla.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.flask.oauth2.sqla.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