Server Reference

This part of the documentation covers the interface of Authlib Server.

Flask OAuth 2 Server

class authlib.flask.oauth2.AuthorizationServer(client_model, app=None)

Flask implementation of authlib.rfc6749.AuthorizationServer. Initialize it with a client model class and Flask app instance:

server = AuthorizationServer(OAuth2Client, app)
# or initialize lazily
server = AuthorizationServer(OAuth2Client)
server.init_app(app)
create_authorization_response(user)

Create the HTTP response for authorization. If resource owner granted the authorization, pass the resource owner as the user parameter, otherwise None:

@app.route('/authorize', methods=['POST'])
def confirm_authorize():
    if request.form['confirm'] == 'ok':
        user = current_user
    else:
        user = None
    return server.create_authorization_response(user)
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_expires_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_EXPIRES_{{grant_type|upper}}.

create_revocation_response()

Create HTTP response for revocation endpoint. register_revoke_token_endpoint() is required before using this method. It is ready to use, as simple as:

@app.route('/token/revoke', methods=['POST'])
def revoke_token():
    return server.create_revocation_response()
create_token_response()

Create the HTTP response for token endpoint. It is ready to use, as simple as:

@app.route('/token', methods=['POST'])
def issue_token():
    return server.create_token_response()
register_grant_endpoint(grant_cls)

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

class MyImplicitGrant(ImplicitGrant):
    def create_access_token(self, token, client, grant_user):
        # ...

authorization_server.register_grant_endpoint(MyImplicitGrant)
Parameters:grant_cls – a grant class.
register_revoke_token_endpoint(cls)

Add revoke token support for authorization server. Revoke token is defined by RFC7009, implemented with authlib.specs.rfc7009.RevocationEndpoint.

validate_authorization_request()

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_authorization_request()
        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(query_token, realm=None, validator_cls=None)

A protecting method for resource servers. Initialize a resource protector with the query_token method:

from authlib.flask.oauth2 import ResourceProtector, current_token
from your_project.models import Token, User

def query_token(cls, access_token):
    return Token.query.filter_by(access_token=access_token).first()

require_oauth= ResourceProtector(query_token)

@app.route('/user')
@require_oauth('profile')
def user_profile():
    user = User.query.get(current_token.user_id)
    return jsonify(user.to_dict())
Parameters:
  • query_token – a function to query token model by access_token string.
  • realm – a string to represent realm value. Default is None.
  • validator_cls – a token validator class. Default is authlib.flask.oauth2.BearerTokenValidator.
authenticate_token(token_string, token_type)

Authenticate token in Authorization header. Only Bearer Token is supported for now.

class authlib.flask.oauth2.BearerTokenValidator(realm=None)

A default Bearer token validator. Simple but ready to use.

request_invalid(method, uri, body, headers)

Validate if current HTTP request is valid. It always return False. Developers who want to validate the HTTP request can re-implement it with authlib.specs.rfc6750.BearerTokenValidator.

token_revoked(token)

Validate if current token is revoked. It always return False. Developers who want to validate token revoked can re-implement it with authlib.specs.rfc6750.BearerTokenValidator.

authlib.flask.oauth2.current_token

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