Server Reference

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

Flask OAuth 1.0 Server

class authlib.flask.oauth1.AuthorizationServer(app=None, query_client=None, token_generator=None)

Flask implementation of authlib.rfc5849.AuthorizationServer. Initialize it with Flask app instance, client model class and cache:

server = AuthorizationServer(app=app, query_client=query_client)
# or initialize lazily
server = AuthorizationServer()
server.init_app(app, query_client=query_client)
Parameters:
  • app – A Flask app instance
  • query_client – A function to get client by client_id. The client model class MUST implement the methods described by ClientMixin.
  • token_generator – A function to generate token
create_authorization_response(request=None, grant_user=None)

Validate authorization request and create authorization response. Assume the endpoint for authorization request is https://photos.example.net/authorize, the client redirects Jane’s user-agent to the server’s Resource Owner Authorization endpoint to obtain Jane’s approval for accessing her private photos:

https://photos.example.net/authorize?oauth_token=hh5s93j4hdidpola

The server requests Jane to sign in using her username and password and if successful, asks her to approve granting ‘printer.example.com’ access to her private photos. Jane approves the request and her user-agent is redirected to the callback URI provided by the client in the previous request (line breaks are for display purposes only):

http://printer.example.com/ready?
oauth_token=hh5s93j4hdidpola&oauth_verifier=hfdp7dh39dks9884
Parameters:
  • request – OAuth1Request instance.
  • grant_user – if granted, pass the grant user, otherwise None.
Returns:

(status_code, body, headers)

create_authorization_verifier(request)

Create and bind oauth_verifier to temporary credential. It could be re-implemented in this way:

def create_authorization_verifier(self, request):
    verifier = generate_token(36)

    temporary_credential = request.credential
    user_id = request.user.get_user_id()

    temporary_credential.user_id = user_id
    temporary_credential.oauth_verifier = verifier
    # if the credential has a save method
    temporary_credential.save()

    # remember to return the verifier
    return verifier
Parameters:request – OAuth1Request instance
Returns:A string of oauth_verifier
create_temporary_credential(request)

Generate and save a temporary credential into database or cache. A temporary credential is used for exchanging token credential. This method should be re-implemented:

def create_temporary_credential(self, request):
    oauth_token = generate_token(36)
    oauth_token_secret = generate_token(48)
    temporary_credential = TemporaryCredential(
        oauth_token=oauth_token,
        oauth_token_secret=oauth_token_secret,
        client_id=request.client_id,
        redirect_uri=request.redirect_uri,
    )
    # if the credential has a save method
    temporary_credential.save()
    return temporary_credential
Parameters:request – OAuth1Request instance
Returns:TemporaryCredential instance
create_temporary_credentials_response(request=None)

Validate temporary credentials token request and create response for temporary credentials token. Assume the endpoint of temporary credentials request is https://photos.example.net/initiate:

POST /initiate HTTP/1.1
Host: photos.example.net
Authorization: OAuth realm="Photos",
    oauth_consumer_key="dpf43f3p2l4k3l03",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp="137131200",
    oauth_nonce="wIjqoS",
    oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready",
    oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D"

The server validates the request and replies with a set of temporary credentials in the body of the HTTP response:

HTTP/1.1 200 OK
Content-Type: application/x-www-form-urlencoded

oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&
oauth_callback_confirmed=true
Parameters:request – OAuth1Request instance.
Returns:(status_code, body, headers)
create_token_credential(request)

Create and save token credential into database. This method would be re-implemented like this:

def create_token_credential(self, request):
    oauth_token = generate_token(36)
    oauth_token_secret = generate_token(48)
    temporary_credential = request.credential

    token_credential = TokenCredential(
        oauth_token=oauth_token,
        oauth_token_secret=oauth_token_secret,
        client_id=temporary_credential.get_client_id(),
        user_id=temporary_credential.get_user_id()
    )
    # if the credential has a save method
    token_credential.save()
    return token_credential
Parameters:request – OAuth1Request instance
Returns:TokenCredential instance
create_token_response(request=None)

Validate token request and create token response. Assuming the endpoint of token request is https://photos.example.net/token, the callback request informs the client that Jane completed the authorization process. The client then requests a set of token credentials using its temporary credentials (over a secure Transport Layer Security (TLS) channel):

POST /token HTTP/1.1
Host: photos.example.net
Authorization: OAuth realm="Photos",
    oauth_consumer_key="dpf43f3p2l4k3l03",
    oauth_token="hh5s93j4hdidpola",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp="137131201",
    oauth_nonce="walatlh",
    oauth_verifier="hfdp7dh39dks9884",
    oauth_signature="gKgrFCywp7rO0OXSjdot%2FIHF7IU%3D"

The server validates the request and replies with a set of token credentials in the body of the HTTP response:

HTTP/1.1 200 OK
Content-Type: application/x-www-form-urlencoded

oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00
Parameters:request – OAuth1Request instance.
Returns:(status_code, body, headers)
delete_temporary_credential(request)

Delete temporary credential from database or cache. For instance, if temporary credential is saved in cache:

def delete_temporary_credential(self, request):
    key = 'a-key-prefix:{}'.format(request.token)
    cache.delete(key)
Parameters:request – OAuth1Request instance
exists_nonce(nonce, request)

The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations.

Parameters:
  • nonce – A string value of oauth_nonce
  • request – OAuth1Request instance
Returns:

Boolean

get_client_by_id(client_id)

Get client instance with the given client_id.

Parameters:client_id – A string of client_id
Returns:Client instance
get_temporary_credential(request)

Get the temporary credential from database or cache. A temporary credential should share the same methods as described in models of TemporaryCredentialMixin:

def get_temporary_credential(self, request):
    key = 'a-key-prefix:{}'.format(request.token)
    data = cache.get(key)
    # TemporaryCredential shares methods from TemporaryCredentialMixin
    return TemporaryCredential(data)
Parameters:request – OAuth1Request instance
Returns:TemporaryCredential instance
class authlib.flask.oauth1.ResourceProtector(app=None, query_client=None, query_token=None, exists_nonce=None)

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

from authlib.flask.oauth1 import ResourceProtector, current_credential
from authlib.flask.oauth1.cache import create_exists_nonce_func
from authlib.flask.oauth1.sqla import (
    create_query_client_func,
    create_query_token_func,
)
from your_project.models import Token, User, cache

# you need to define a ``cache`` instance yourself

require_oauth= ResourceProtector(
    app,
    query_client=create_query_client_func(db.session, OAuth1Client),
    query_token=create_query_token_func(db.session, OAuth1Token),
    exists_nonce=create_exists_nonce_func(cache)
)
# or initialize it lazily
require_oauth = ResourceProtector()
require_oauth.init_app(
    app,
    query_client=create_query_client_func(db.session, OAuth1Client),
    query_token=create_query_token_func(db.session, OAuth1Token),
    exists_nonce=create_exists_nonce_func(cache)
)
get_client_by_id(client_id)

Get client instance with the given client_id.

Parameters:client_id – A string of client_id
Returns:Client instance
exists_nonce(nonce, request)

The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations.

Parameters:
  • nonce – A string value of oauth_nonce
  • request – OAuth1Request instance
Returns:

Boolean

authlib.flask.oauth1.current_credential

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

Cache Helper Functions

authlib.flask.oauth1.cache.create_exists_nonce_func(cache, key_prefix='nonce:', expires=86400)

Create an exists_nonce function that can be used in hooks and resource protector.

Parameters:
  • cache – Cache instance
  • key_prefix – key prefix for temporary credential
  • expires – Expire time for nonce
authlib.flask.oauth1.cache.register_nonce_hooks(authorization_server, cache, key_prefix='nonce:', expires=86400)

Register nonce related hooks to authorization server.

Parameters:
  • authorization_server – AuthorizationServer instance
  • cache – Cache instance
  • key_prefix – key prefix for temporary credential
  • expires – Expire time for nonce
authlib.flask.oauth1.cache.register_temporary_credential_hooks(authorization_server, cache, key_prefix='temporary_credential:')

Register temporary credential related hooks to authorization server.

Parameters:
  • authorization_server – AuthorizationServer instance
  • cache – Cache instance
  • key_prefix – key prefix for temporary credential

SQLAlchemy Help Functions

authlib.flask.oauth1.sqla.create_query_client_func(session, model_class)

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

Parameters:
  • session – SQLAlchemy session
  • model_class – Client class
authlib.flask.oauth1.sqla.create_query_token_func(session, model_class)

Create an query_token function that can be used in resource protector.

Parameters:
  • session – SQLAlchemy session
  • model_class – TokenCredential class
authlib.flask.oauth1.sqla.create_exists_nonce_func(session, model_class)

Create an exists_nonce function that can be used in hooks and resource protector.

Parameters:
  • session – SQLAlchemy session
  • model_class – TimestampNonce class
authlib.flask.oauth1.sqla.register_nonce_hooks(authorization_server, session, model_class)

Register nonce related hooks to authorization server.

Parameters:
  • authorization_server – AuthorizationServer instance
  • session – SQLAlchemy session
  • model_class – TimestampNonce class
authlib.flask.oauth1.sqla.register_temporary_credential_hooks(authorization_server, session, model_class)

Register temporary credential related hooks to authorization server.

Parameters:
  • authorization_server – AuthorizationServer instance
  • session – SQLAlchemy session
  • model_class – TemporaryCredential class
authlib.flask.oauth1.sqla.register_token_credential_hooks(authorization_server, session, model_class)

Register token credential related hooks to authorization server.

Parameters:
  • authorization_server – AuthorizationServer instance
  • session – SQLAlchemy session
  • model_class – TokenCredential class

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_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_grant(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 AuthorizationCodeGrant(grants.AuthorizationCodeGrant):
    def authenticate_user(self, credential):
        # ...

authorization_server.register_grant(AuthorizationCodeGrant)
Parameters:grant_cls – a 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

ResourceProtector.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())
acquire_token(scope=None)

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

Parameters:scope – resource scope value
Returns:token object
acquire(scope=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.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

Django OAuth 1.0 Server

class authlib.django.oauth1.CacheAuthorizationServer(client_model, token_model, token_generator=None)
create_authorization_response(request, grant_user=None)

Validate authorization request and create authorization response. Assume the endpoint for authorization request is https://photos.example.net/authorize, the client redirects Jane’s user-agent to the server’s Resource Owner Authorization endpoint to obtain Jane’s approval for accessing her private photos:

https://photos.example.net/authorize?oauth_token=hh5s93j4hdidpola

The server requests Jane to sign in using her username and password and if successful, asks her to approve granting ‘printer.example.com’ access to her private photos. Jane approves the request and her user-agent is redirected to the callback URI provided by the client in the previous request (line breaks are for display purposes only):

http://printer.example.com/ready?
oauth_token=hh5s93j4hdidpola&oauth_verifier=hfdp7dh39dks9884
Parameters:
  • request – OAuth1Request instance.
  • grant_user – if granted, pass the grant user, otherwise None.
Returns:

(status_code, body, headers)

create_authorization_verifier(request)

Create and bind oauth_verifier to temporary credential. It could be re-implemented in this way:

def create_authorization_verifier(self, request):
    verifier = generate_token(36)

    temporary_credential = request.credential
    user_id = request.user.get_user_id()

    temporary_credential.user_id = user_id
    temporary_credential.oauth_verifier = verifier
    # if the credential has a save method
    temporary_credential.save()

    # remember to return the verifier
    return verifier
Parameters:request – OAuth1Request instance
Returns:A string of oauth_verifier
create_temporary_credential(request)

Generate and save a temporary credential into database or cache. A temporary credential is used for exchanging token credential. This method should be re-implemented:

def create_temporary_credential(self, request):
    oauth_token = generate_token(36)
    oauth_token_secret = generate_token(48)
    temporary_credential = TemporaryCredential(
        oauth_token=oauth_token,
        oauth_token_secret=oauth_token_secret,
        client_id=request.client_id,
        redirect_uri=request.redirect_uri,
    )
    # if the credential has a save method
    temporary_credential.save()
    return temporary_credential
Parameters:request – OAuth1Request instance
Returns:TemporaryCredential instance
create_temporary_credentials_response(request)

Validate temporary credentials token request and create response for temporary credentials token. Assume the endpoint of temporary credentials request is https://photos.example.net/initiate:

POST /initiate HTTP/1.1
Host: photos.example.net
Authorization: OAuth realm="Photos",
    oauth_consumer_key="dpf43f3p2l4k3l03",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp="137131200",
    oauth_nonce="wIjqoS",
    oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready",
    oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D"

The server validates the request and replies with a set of temporary credentials in the body of the HTTP response:

HTTP/1.1 200 OK
Content-Type: application/x-www-form-urlencoded

oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&
oauth_callback_confirmed=true
Parameters:request – OAuth1Request instance.
Returns:(status_code, body, headers)
create_token_credential(request)

Create and save token credential into database. This method would be re-implemented like this:

def create_token_credential(self, request):
    oauth_token = generate_token(36)
    oauth_token_secret = generate_token(48)
    temporary_credential = request.credential

    token_credential = TokenCredential(
        oauth_token=oauth_token,
        oauth_token_secret=oauth_token_secret,
        client_id=temporary_credential.get_client_id(),
        user_id=temporary_credential.get_user_id()
    )
    # if the credential has a save method
    token_credential.save()
    return token_credential
Parameters:request – OAuth1Request instance
Returns:TokenCredential instance
create_token_response(request)

Validate token request and create token response. Assuming the endpoint of token request is https://photos.example.net/token, the callback request informs the client that Jane completed the authorization process. The client then requests a set of token credentials using its temporary credentials (over a secure Transport Layer Security (TLS) channel):

POST /token HTTP/1.1
Host: photos.example.net
Authorization: OAuth realm="Photos",
    oauth_consumer_key="dpf43f3p2l4k3l03",
    oauth_token="hh5s93j4hdidpola",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp="137131201",
    oauth_nonce="walatlh",
    oauth_verifier="hfdp7dh39dks9884",
    oauth_signature="gKgrFCywp7rO0OXSjdot%2FIHF7IU%3D"

The server validates the request and replies with a set of token credentials in the body of the HTTP response:

HTTP/1.1 200 OK
Content-Type: application/x-www-form-urlencoded

oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00
Parameters:request – OAuth1Request instance.
Returns:(status_code, body, headers)
delete_temporary_credential(request)

Delete temporary credential from database or cache. For instance, if temporary credential is saved in cache:

def delete_temporary_credential(self, request):
    key = 'a-key-prefix:{}'.format(request.token)
    cache.delete(key)
Parameters:request – OAuth1Request instance
exists_nonce(nonce, request)

The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations.

Parameters:
  • nonce – A string value of oauth_nonce
  • request – OAuth1Request instance
Returns:

Boolean

get_client_by_id(client_id)

Get client instance with the given client_id.

Parameters:client_id – A string of client_id
Returns:Client instance
get_temporary_credential(request)

Get the temporary credential from database or cache. A temporary credential should share the same methods as described in models of TemporaryCredentialMixin:

def get_temporary_credential(self, request):
    key = 'a-key-prefix:{}'.format(request.token)
    data = cache.get(key)
    # TemporaryCredential shares methods from TemporaryCredentialMixin
    return TemporaryCredential(data)
Parameters:request – OAuth1Request instance
Returns:TemporaryCredential instance
classmethod register_signature_method(name, verify)

Extend signature method verification.

Parameters:
  • name – A string to represent signature method.
  • verify – A function to verify signature.

The verify method accept OAuth1Request as parameter:

def verify_custom_method(request):
    # verify this request, return True or False
    return True

Server.register_signature_method('custom-name', verify_custom_method)
validate_authorization_request(request)

Validate the request for resource owner authorization.

validate_oauth_signature(request)

Validate oauth_signature from HTTP request.

Parameters:request – OAuth1Request instance
validate_temporary_credentials_request(request)

Validate HTTP request for temporary credentials.

validate_timestamp_and_nonce(request)

Validate oauth_timestamp and oauth_nonce in HTTP request.

Parameters:request – OAuth1Request instance
validate_token_request(request)

Validate request for issuing token.

class authlib.django.oauth1.ResourceProtector(client_model, token_model)
get_client_by_id(client_id)

Get client instance with the given client_id.

Parameters:client_id – A string of client_id
Returns:Client instance
exists_nonce(nonce, request)

The nonce value MUST be unique across all requests with the same timestamp, client credentials, and token combinations.

Parameters:
  • nonce – A string value of oauth_nonce
  • request – OAuth1Request instance
Returns:

Boolean