Developer Interface

This part of the documentation covers the interface of Flask-OAuthlib.

Client Reference

class flask_oauthlib.client.OAuth(app=None)

Registry for remote applications.

Parameters:app – the app instance of Flask

Create an instance with Flask:

oauth = OAuth(app)
init_app(app)

Init app with Flask instance.

You can also pass the instance of Flask later:

oauth = OAuth()
oauth.init_app(app)
remote_app(name, register=True, **kwargs)

Registers a new remote application.

Parameters:
  • name – the name of the remote application
  • register – whether the remote app will be registered

Find more parameters from OAuthRemoteApp.

class flask_oauthlib.client.OAuthRemoteApp(oauth, name, base_url=None, request_token_url=None, access_token_url=None, authorize_url=None, consumer_key=None, consumer_secret=None, request_token_params=None, request_token_method=None, access_token_params=None, access_token_method=None, access_token_headers=None, content_type=None, app_key=None, encoding='utf-8')

Represents a remote application.

Parameters:
  • oauth – the associated OAuth object
  • name – the name of the remote application
  • base_url – the base url for every request
  • request_token_url – the url for requesting new tokens
  • access_token_url – the url for token exchange
  • authorize_url – the url for authorization
  • consumer_key – the application specific consumer key
  • consumer_secret – the application specific consumer secret
  • request_token_params – an optional dictionary of parameters to forward to the request token url or authorize url depending on oauth version
  • request_token_method – the HTTP method that should be used for the access_token_url. Default is GET
  • access_token_params – an optional dictionary of parameters to forward to the access token url
  • access_token_method – the HTTP method that should be used for the access_token_url. Default is GET
  • access_token_headers – additonal headers that should be used for the access_token_url.
  • content_type – force to parse the content with this content_type, usually used when the server didn’t return the right content type.

New in version 0.3.0.

Parameters:app_key – lazy load configuration from Flask app config with this app key
authorize(callback=None, state=None, **kwargs)

Returns a redirect response to the remote authorization URL with the signed callback given.

Parameters:
  • callback – a redirect url for the callback
  • state – an optional value to embed in the OAuth request. Use this if you want to pass around application state (e.g. CSRF tokens).
  • kwargs – add optional key/value pairs to the query string
authorized_handler(f)

Handles an OAuth callback.

Changed in version 0.7: @authorized_handler is deprecated in favor of authorized_response.

authorized_response()

Handles authorization response smartly.

delete(*args, **kwargs)

Sends a DELETE request. Accepts the same parameters as request().

get(*args, **kwargs)

Sends a GET request. Accepts the same parameters as request().

handle_oauth1_response()

Handles an oauth1 authorization response.

handle_oauth2_response()

Handles an oauth2 authorization response.

handle_unknown_response()

Handles a unknown authorization response.

patch(*args, **kwargs)

Sends a PATCH request. Accepts the same parameters as post().

post(*args, **kwargs)

Sends a POST request. Accepts the same parameters as request().

put(*args, **kwargs)

Sends a PUT request. Accepts the same parameters as request().

request(url, data=None, headers=None, format='urlencoded', method='GET', content_type=None, token=None)

Sends a request to the remote server with OAuth tokens attached.

Parameters:
  • data – the data to be sent to the server.
  • headers – an optional dictionary of headers.
  • format – the format for the data. Can be urlencoded for URL encoded data or json for JSON.
  • method – the HTTP request method to use.
  • content_type – an optional content type. If a content type is provided, the data is passed as it, and the format is ignored.
  • token – an optional token to pass, if it is None, token will be generated by tokengetter.
tokengetter(f)

Register a function as token getter.

class flask_oauthlib.client.OAuthResponse(resp, content, content_type=None)
status

The status code of the response.

class flask_oauthlib.client.OAuthException(message, type=None, data=None)

OAuth1 Provider

class flask_oauthlib.provider.OAuth1Provider(app=None)

Provide secure services using OAuth1.

Like many other Flask extensions, there are two usage modes. One is binding the Flask app instance:

app = Flask(__name__)
oauth = OAuth1Provider(app)

The second possibility is to bind the Flask app later:

oauth = OAuth1Provider()

def create_app():
    app = Flask(__name__)
    oauth.init_app(app)
    return app

And now you can protect the resource with realms:

@app.route('/api/user')
@oauth.require_oauth('email', 'username')
def user():
    return jsonify(request.oauth.user)
access_token_handler(f)

Access token handler decorator.

The decorated function should return an dictionary or None as the extra credentials for creating the token response.

If you don’t need to add any extra credentials, it could be as simple as:

@app.route('/oauth/access_token')
@oauth.access_token_handler
def access_token():
    return {}
after_request(f)

Register functions to be invoked after accessing the resource.

The function accepts valid and request as parameters, and it should return a tuple of them:

@oauth.after_request
def valid_after_request(valid, oauth):
    if oauth.user in black_list:
        return False, oauth
    return valid, oauth
authorize_handler(f)

Authorization handler decorator.

This decorator will sort the parameters and headers out, and pre validate everything:

@app.route('/oauth/authorize', methods=['GET', 'POST'])
@oauth.authorize_handler
def authorize(*args, **kwargs):
    if request.method == 'GET':
        # render a page for user to confirm the authorization
        return render_template('oauthorize.html')

    confirm = request.form.get('confirm', 'no')
    return confirm == 'yes'
before_request(f)

Register functions to be invoked before accessing the resource.

The function accepts nothing as parameters, but you can get information from Flask.request object. It is usually useful for setting limitation on the client request:

@oauth.before_request
def limit_client_request():
    client_key = request.values.get('client_key')
    if not client_key:
        return
    client = Client.get(client_key)
    if over_limit(client):
        return abort(403)

    track_request(client)
clientgetter(f)

Register a function as the client getter.

The function accepts one parameter client_key, and it returns a client object with at least these information:

  • client_key: A random string
  • client_secret: A random string
  • redirect_uris: A list of redirect uris
  • default_realms: Default scopes of the client

The client may contain more information, which is suggested:

  • default_redirect_uri: One of the redirect uris

Implement the client getter:

@oauth.clientgetter
def get_client(client_key):
    client = get_client_model(client_key)
    # Client is an object
    return client
confirm_authorization_request()

When consumer confirm the authrozation.

error_uri

The error page URI.

When something turns error, it will redirect to this error page. You can configure the error page URI with Flask config:

OAUTH1_PROVIDER_ERROR_URI = '/error'

You can also define the error page by a named endpoint:

OAUTH1_PROVIDER_ERROR_ENDPOINT = 'oauth.error'
grantgetter(f)

Register a function as the request token getter.

The function accepts a token parameter, and it returns an request token object contains:

  • client: Client associated with this token
  • token: Access token
  • secret: Access token secret
  • realms: Realms with this access token
  • redirect_uri: A URI for redirecting

Implement the token getter:

@oauth.tokengetter
def get_request_token(token):
    return RequestToken.get(token=token)
grantsetter(f)

Register a function as the request token setter.

The setter accepts a token and request parameters:

@oauth.grantsetter
def save_request_token(token, request):
    data = RequestToken(
        token=token['oauth_token'],
        secret=token['oauth_token_secret'],
        client=request.client,
        redirect_uri=oauth.redirect_uri,
        realms=request.realms,
    )
    return data.save()
init_app(app)

This callback can be used to initialize an application for the oauth provider instance.

noncegetter(f)

Register a function as the nonce and timestamp getter.

The function accepts parameters:

  • client_key: The client/consure key
  • timestamp: The oauth_timestamp parameter
  • nonce: The oauth_nonce parameter
  • request_token: Request token string, if any
  • access_token: Access token string, if any

A nonce and timestamp make each request unique. The implementation:

@oauth.noncegetter
def get_nonce(client_key, timestamp, nonce, request_token,
              access_token):
    return Nonce.get("...")
noncesetter(f)

Register a function as the nonce and timestamp setter.

The parameters are the same with noncegetter():

@oauth.noncegetter
def save_nonce(client_key, timestamp, nonce, request_token,
               access_token):
    data = Nonce("...")
    return data.save()

The timestamp will be expired in 60s, it would be a better design if you put timestamp and nonce object in a cache.

request_token_handler(f)

Request token handler decorator.

The decorated function should return an dictionary or None as the extra credentials for creating the token response.

If you don’t need to add any extra credentials, it could be as simple as:

@app.route('/oauth/request_token')
@oauth.request_token_handler
def request_token():
    return {}
require_oauth(*realms, **kwargs)

Protect resource with specified scopes.

server

All in one endpoints. This property is created automaticly if you have implemented all the getters and setters.

tokengetter(f)

Register a function as the access token getter.

The function accepts client_key and token parameters, and it returns an access token object contains:

  • client: Client associated with this token
  • user: User associated with this token
  • token: Access token
  • secret: Access token secret
  • realms: Realms with this access token

Implement the token getter:

@oauth.tokengetter
def get_access_token(client_key, token):
    return AccessToken.get(client_key=client_key, token=token)
tokensetter(f)

Register a function as the access token setter.

The setter accepts two parameters at least, one is token, the other is request:

@oauth.tokensetter
def save_access_token(token, request):
    access_token = AccessToken(
        client=request.client,
        user=request.user,
        token=token['oauth_token'],
        secret=token['oauth_token_secret'],
        realms=token['oauth_authorized_realms'].split(' '),
    )
    return access_token.save()

The parameter token is a dict, that looks like:

{
    u'oauth_token': u'arandomstringoftoken',
    u'oauth_token_secret': u'arandomstringofsecret',
    u'oauth_authorized_realms': u'email address'
}

The request object would provide these information (at least):

- client: Client object associated with this token
- user: User object associated with this token
- request_token: Requst token for exchanging this access token
verifiergetter(f)

Register a function as the verifier getter.

The return verifier object should at least contain a user object which is the current user.

The implemented code looks like:

@oauth.verifiergetter
def load_verifier(verifier, token):
    data = Verifier.get(verifier)
    if data.request_token == token:
        # check verifier for safety
        return data
    return data
verifiersetter(f)

Register a function as the verifier setter.

A verifier is better together with request token, but it is not required. A verifier is used together with request token for exchanging access token, it has an expire time, in this case, it would be a better design if you put them in a cache.

The implemented code looks like:

@oauth.verifiersetter
def save_verifier(verifier, token, *args, **kwargs):
    data = Verifier(
        verifier=verifier['oauth_verifier'],
        request_token=token,
        user=get_current_user()
    )
    return data.save()
class flask_oauthlib.provider.OAuth1RequestValidator(clientgetter, tokengetter, tokensetter, grantgetter, grantsetter, noncegetter, noncesetter, verifiergetter, verifiersetter, config=None)

Subclass of Request Validator.

Parameters:
  • clientgetter – a function to get client object
  • tokengetter – a function to get access token
  • tokensetter – a function to save access token
  • grantgetter – a function to get request token
  • grantsetter – a function to save request token
  • noncegetter – a function to get nonce and timestamp
  • noncesetter – a function to save nonce and timestamp
allowed_signature_methods

Allowed signature methods.

Default value: SIGNATURE_HMAC and SIGNATURE_RSA.

You can customize with Flask Config:

  • OAUTH1_PROVIDER_SIGNATURE_METHODS
enforce_ssl

Enforce SSL request.

Default is True. You can customize with:

  • OAUTH1_PROVIDER_ENFORCE_SSL
get_access_token_secret(client_key, token, request)

Get access token secret.

The access token object should a secret attribute.

get_client_secret(client_key, request)

Get client secret.

The client object must has client_secret attribute.

get_default_realms(client_key, request)

Default realms of the client.

get_realms(token, request)

Realms for this request token.

get_redirect_uri(token, request)

Redirect uri for this request token.

get_request_token_secret(client_key, token, request)

Get request token secret.

The request token object should a secret attribute.

get_rsa_key(client_key, request)

Retrieves a previously stored client provided RSA key.

invalidate_request_token(client_key, request_token, request)

Invalidates a used request token.

save_access_token(token, request)

Save access token to database.

A tokensetter is required, which accepts a token and request parameters:

def tokensetter(token, request):
    access_token = Token(
        client=request.client,
        user=request.user,
        token=token['oauth_token'],
        secret=token['oauth_token_secret'],
        realms=token['oauth_authorized_realms'],
    )
    return access_token.save()
save_request_token(token, request)

Save request token to database.

A grantsetter is required, which accepts a token and request parameters:

def grantsetter(token, request):
    grant = Grant(
        token=token['oauth_token'],
        secret=token['oauth_token_secret'],
        client=request.client,
        redirect_uri=oauth.redirect_uri,
        realms=request.realms,
    )
    return grant.save()
save_verifier(token, verifier, request)

Save verifier to database.

A verifiersetter is required. It would be better to combine request token and verifier together:

def verifiersetter(token, verifier, request):
    tok = Grant.query.filter_by(token=token).first()
    tok.verifier = verifier['oauth_verifier']
    tok.user = get_current_user()
    return tok.save()

Note:

A user is required on verifier, remember to attach current user to verifier.

validate_access_token(client_key, token, request)

Validates access token is available for client.

validate_client_key(client_key, request)

Validates that supplied client key.

validate_realms(client_key, token, request, uri=None, realms=None)

Check if the token has permission on those realms.

validate_redirect_uri(client_key, redirect_uri, request)

Validate if the redirect_uri is allowed by the client.

validate_request_token(client_key, token, request)

Validates request token is available for client.

validate_timestamp_and_nonce(client_key, timestamp, nonce, request, request_token=None, access_token=None)

Validate the timestamp and nonce is used or not.

validate_verifier(client_key, token, verifier, request)

Validate verifier exists.

verify_realms(token, realms, request)

Verify if the realms match the requested realms.

verify_request_token(token, request)

Verify if the request token is existed.

OAuth2 Provider

class flask_oauthlib.provider.OAuth2Provider(app=None)

Provide secure services using OAuth2.

The server should provide an authorize handler and a token hander, But before the handlers are implemented, the server should provide some getters for the validation.

Like many other Flask extensions, there are two usage modes. One is binding the Flask app instance:

app = Flask(__name__)
oauth = OAuth2Provider(app)

The second possibility is to bind the Flask app later:

oauth = OAuth2Provider()

def create_app():
    app = Flask(__name__)
    oauth.init_app(app)
    return app

Configure tokengetter() and tokensetter() to get and set tokens. Configure grantgetter() and grantsetter() to get and set grant tokens. Configure clientgetter() to get the client.

Configure usergetter() if you need password credential authorization.

With everything ready, implement the authorization workflow:

And now you can protect the resource with scopes:

@app.route('/api/user')
@oauth.require_oauth('email', 'username')
def user():
    return jsonify(request.oauth.user)
after_request(f)

Register functions to be invoked after accessing the resource.

The function accepts valid and request as parameters, and it should return a tuple of them:

@oauth.after_request
def valid_after_request(valid, oauth):
    if oauth.user in black_list:
        return False, oauth
    return valid, oauth
authorize_handler(f)

Authorization handler decorator.

This decorator will sort the parameters and headers out, and pre validate everything:

@app.route('/oauth/authorize', methods=['GET', 'POST'])
@oauth.authorize_handler
def authorize(*args, **kwargs):
    if request.method == 'GET':
        # render a page for user to confirm the authorization
        return render_template('oauthorize.html')

    confirm = request.form.get('confirm', 'no')
    return confirm == 'yes'
before_request(f)

Register functions to be invoked before accessing the resource.

The function accepts nothing as parameters, but you can get information from Flask.request object. It is usually useful for setting limitation on the client request:

@oauth.before_request
def limit_client_request():
    client_id = request.values.get('client_id')
    if not client_id:
        return
    client = Client.get(client_id)
    if over_limit(client):
        return abort(403)

    track_request(client)
clientgetter(f)

Register a function as the client getter.

The function accepts one parameter client_id, and it returns a client object with at least these information:

  • client_id: A random string
  • client_secret: A random string
  • is_confidential: A bool represents if it is confidential
  • redirect_uris: A list of redirect uris
  • default_redirect_uri: One of the redirect uris
  • default_scopes: Default scopes of the client

The client may contain more information, which is suggested:

  • allowed_grant_types: A list of grant types
  • allowed_response_types: A list of response types
  • validate_scopes: A function to validate scopes

Implement the client getter:

@oauth.clientgetter
def get_client(client_id):
    client = get_client_model(client_id)
    # Client is an object
    return client
confirm_authorization_request()

When consumer confirm the authorization.

error_uri

The error page URI.

When something turns error, it will redirect to this error page. You can configure the error page URI with Flask config:

OAUTH2_PROVIDER_ERROR_URI = '/error'

You can also define the error page by a named endpoint:

OAUTH2_PROVIDER_ERROR_ENDPOINT = 'oauth.error'
grantgetter(f)

Register a function as the grant getter.

The function accepts client_id, code and more:

@oauth.grantgetter
def grant(client_id, code):
    return get_grant(client_id, code)

It returns a grant object with at least these information:

  • delete: A function to delete itself
grantsetter(f)

Register a function to save the grant code.

The function accepts client_id, code, request and more:

@oauth.grantsetter
def set_grant(client_id, code, request, *args, **kwargs):
    save_grant(client_id, code, request.user, request.scopes)
init_app(app)

This callback can be used to initialize an application for the oauth provider instance.

invalid_response(f)

Register a function for responsing with invalid request.

When an invalid request proceeds to require_oauth(), we can handle the request with the registered function. The function accepts one parameter, which is an oauthlib Request object:

@oauth.invalid_response
def invalid_require_oauth(req):
    return jsonify(message=req.error_message), 401

If no function is registered, it will return with abort(401).

require_oauth(*scopes)

Protect resource with specified scopes.

revoke_handler(f)

Access/refresh token revoke decorator.

Any return value by the decorated function will get discarded as defined in [RFC7009].

You can control the access method with the standard flask routing mechanism, as per [RFC7009] it is recommended to only allow the POST method:

@app.route('/oauth/revoke', methods=['POST'])
@oauth.revoke_handler
def revoke_token():
    pass
server

All in one endpoints. This property is created automaticly if you have implemented all the getters and setters.

However, if you are not satisfied with the getter and setter, you can create a validator with OAuth2RequestValidator:

class MyValidator(OAuth2RequestValidator):
    def validate_client_id(self, client_id):
        # do something
        return True

And assign the validator for the provider:

oauth._validator = MyValidator()
token_handler(f)

Access/refresh token handler decorator.

The decorated function should return an dictionary or None as the extra credentials for creating the token response.

You can control the access method with standard flask route mechanism. If you only allow the POST method:

@app.route('/oauth/token', methods=['POST'])
@oauth.token_handler
def access_token():
    return None
tokengetter(f)

Register a function as the token getter.

The function accepts an access_token or refresh_token parameters, and it returns a token object with at least these information:

  • access_token: A string token
  • refresh_token: A string token
  • client_id: ID of the client
  • scopes: A list of scopes
  • expires: A datetime.datetime object
  • user: The user object

The implementation of tokengetter should accepts two parameters, one is access_token the other is refresh_token:

@oauth.tokengetter
def bearer_token(access_token=None, refresh_token=None):
    if access_token:
        return get_token(access_token=access_token)
    if refresh_token:
        return get_token(refresh_token=refresh_token)
    return None
tokensetter(f)

Register a function to save the bearer token.

The setter accepts two parameters at least, one is token, the other is request:

@oauth.tokensetter
def set_token(token, request, *args, **kwargs):
    save_token(token, request.client, request.user)

The parameter token is a dict, that looks like:

{
    u'access_token': u'6JwgO77PApxsFCU8Quz0pnL9s23016',
    u'token_type': u'Bearer',
    u'expires_in': 3600,
    u'scope': u'email address'
}

The request is an object, that contains an user object and a client object.

usergetter(f)

Register a function as the user getter.

This decorator is only required for password credential authorization:

@oauth.usergetter
def get_user(username, password, client, request,
             *args, **kwargs):
    # client: current request client
    if not client.has_password_credential_permission:
        return None
    user = User.get_user_by_username(username)
    if not user.validate_password(password):
        return None

    # parameter `request` is an OAuthlib Request object.
    # maybe you will need it somewhere
    return user
verify_request(scopes)

Verify current request, get the oauth data.

If you can’t use the require_oauth decorator, you can fetch the data in your request body:

def your_handler():
    valid, req = oauth.verify_request(['email'])
    if valid:
        return jsonify(user=req.user)
    return jsonify(status='error')
class flask_oauthlib.provider.OAuth2RequestValidator(clientgetter, tokengetter, grantgetter, usergetter=None, tokensetter=None, grantsetter=None)

Subclass of Request Validator.

Parameters:
  • clientgetter – a function to get client object
  • tokengetter – a function to get bearer token
  • tokensetter – a function to save bearer token
  • grantgetter – a function to get grant token
  • grantsetter – a function to save grant token
authenticate_client(request, *args, **kwargs)

Authenticate itself in other means.

Other means means is described in Section 3.2.1.

authenticate_client_id(client_id, request, *args, **kwargs)

Authenticate a non-confidential client.

Parameters:
  • client_id – Client ID of the non-confidential client
  • request – The Request object passed by oauthlib
client_authentication_required(request, *args, **kwargs)

Determine if client authentication is required for current request.

According to the rfc6749, client authentication is required in the following cases:

Resource Owner Password Credentials Grant: see Section 4.3.2. Authorization Code Grant: see Section 4.1.3. Refresh Token Grant: see Section 6.

confirm_redirect_uri(client_id, code, redirect_uri, client, *args, **kwargs)

Ensure client is authorized to redirect to the redirect_uri.

This method is used in the authorization code grant flow. It will compare redirect_uri and the one in grant token strictly, you can add a validate_redirect_uri function on grant for a customized validation.

confirm_scopes(refresh_token, scopes, request, *args, **kwargs)

Ensures the requested scope matches the scope originally granted by the resource owner. If the scope is omitted it is treated as equal to the scope originally granted by the resource owner.

DEPRECATION NOTE: This method will cease to be used in oauthlib>0.4.2, future versions of oauthlib use the validator method get_original_scopes to determine the scope of the refreshed token.

get_default_redirect_uri(client_id, request, *args, **kwargs)

Default redirect_uri for the given client.

get_default_scopes(client_id, request, *args, **kwargs)

Default scopes for the given client.

get_original_scopes(refresh_token, request, *args, **kwargs)

Get the list of scopes associated with the refresh token.

This method is used in the refresh token grant flow. We return the scope of the token to be refreshed so it can be applied to the new access token.

invalidate_authorization_code(client_id, code, request, *args, **kwargs)

Invalidate an authorization code after use.

We keep the temporary code in a grant, which has a delete function to destroy itself.

revoke_token(token, token_type_hint, request, *args, **kwargs)

Revoke an access or refresh token.

save_authorization_code(client_id, code, request, *args, **kwargs)

Persist the authorization code.

save_bearer_token(token, request, *args, **kwargs)

Persist the Bearer token.

validate_bearer_token(token, scopes, request)

Validate access token.

Parameters:
  • token – A string of random characters
  • scopes – A list of scopes
  • request – The Request object passed by oauthlib

The validation validates:

  1. if the token is available
  2. if the token has expired
  3. if the scopes are available
validate_client_id(client_id, request, *args, **kwargs)

Ensure client_id belong to a valid and active client.

validate_code(client_id, code, client, request, *args, **kwargs)

Ensure the grant code is valid.

validate_grant_type(client_id, grant_type, client, request, *args, **kwargs)

Ensure the client is authorized to use the grant type requested.

It will allow any of the four grant types (authorization_code, password, client_credentials, refresh_token) by default. Implemented allowed_grant_types for client object to authorize the request.

It is suggested that allowed_grant_types should contain at least authorization_code and refresh_token.

validate_redirect_uri(client_id, redirect_uri, request, *args, **kwargs)

Ensure client is authorized to redirect to the redirect_uri.

This method is used in the authorization code grant flow and also in implicit grant flow. It will detect if redirect_uri in client’s redirect_uris strictly, you can add a validate_redirect_uri function on grant for a customized validation.

validate_refresh_token(refresh_token, client, request, *args, **kwargs)

Ensure the token is valid and belongs to the client

This method is used by the authorization code grant indirectly by issuing refresh tokens, resource owner password credentials grant (also indirectly) and the refresh token grant.

validate_response_type(client_id, response_type, client, request, *args, **kwargs)

Ensure client is authorized to use the response type requested.

It will allow any of the two (code, token) response types by default. Implemented allowed_response_types for client object to authorize the request.

validate_scopes(client_id, scopes, client, request, *args, **kwargs)

Ensure the client is authorized access to requested scopes.

validate_user(username, password, client, request, *args, **kwargs)

Ensure the username and password is valid.

Attach user object on request for later using.

Contrib Reference

Here are APIs provided by contributors.

flask_oauthlib.contrib.oauth2.bind_sqlalchemy(provider, session, user=None, client=None, token=None, grant=None, current_user=None)

Configures the given OAuth2Provider instance with the required getters and setters for persistence with SQLAlchemy.

An example of using all models:

oauth = OAuth2Provider(app)

bind_sqlalchemy(oauth, session, user=User, client=Client,
                token=Token, grant=Grant, current_user=current_user)

You can omit any model if you wish to register the functions yourself. It is also possible to override the functions by registering them afterwards:

oauth = OAuth2Provider(app)

bind_sqlalchemy(oauth, session, user=User, client=Client, token=Token)

@oauth.grantgetter
def get_grant(client_id, code):
    pass

@oauth.grantsetter
def set_grant(client_id, code, request, *args, **kwargs):
    pass

# register tokensetter with oauth but keeping the tokengetter
# registered by `SQLAlchemyBinding`
# You would only do this for the token and grant since user and client
# only have getters
@oauth.tokensetter
def set_token(token, request, *args, **kwargs):
    pass

Note that current_user is only required if you’re using SQLAlchemy for grant caching. If you’re using another caching system with GrantCacheBinding instead, omit current_user.

Parameters:
  • providerOAuth2Provider instance
  • session – A Session object
  • userUser model
  • clientClient model
  • tokenToken model
  • grantGrant model
  • current_user – function that returns a User object
flask_oauthlib.contrib.oauth2.bind_cache_grant(app, provider, current_user, config_prefix='OAUTH2')

Configures an OAuth2Provider instance to use various caching systems to get and set the grant token. This removes the need to register grantgetter() and grantsetter() yourself.

Parameters:
  • app – Flask application instance
  • providerOAuth2Provider instance
  • current_user – function that returns an User object
  • config_prefix – prefix for config

A usage example:

oauth = OAuth2Provider(app)
app.config.update({'OAUTH2_CACHE_TYPE': 'redis'})

bind_cache_grant(app, oauth, current_user)

You can define which cache system you would like to use by setting the following configuration option:

OAUTH2_CACHE_TYPE = 'null' // memcache, simple, redis, filesystem

For more information on the supported cache systems please visit: Cache

flask_oauthlib.contrib.apps

The bundle of remote app factories for famous third platforms.

Usage:

from flask import Flask
from flask_oauthlib.client import OAuth
from flask_oauthlib.contrib.apps import github

app = Flask(__name__)
oauth = OAuth(app)

github.register_to(oauth, scope=['user:email'])
github.register_to(oauth, name='github2')

Of course, it requires consumer keys in your config:

GITHUB_CONSUMER_KEY = ''
GITHUB_CONSUMER_SECRET = ''
GITHUB2_CONSUMER_KEY = ''
GITHUB2_CONSUMER_SECRET = ''

Some apps with OAuth 1.0a such as Twitter could not accept the scope argument.

Contributed by: tonyseek

flask_oauthlib.contrib.apps.douban()

The OAuth app for douban.com API.

Parameters:scope – optional. default: ['douban_basic_common']. see also: http://developers.douban.com/wiki/?title=oauth2
flask_oauthlib.contrib.apps.dropbox()

The OAuth app for Dropbox API.

flask_oauthlib.contrib.apps.facebook()

The OAuth app for Facebook API.

Parameters:scope – optional. default: ['email'].
flask_oauthlib.contrib.apps.github()

The OAuth app for GitHub API.

Parameters:scope – optional. default: ['user:email'].
flask_oauthlib.contrib.apps.google()

The OAuth app for Google API.

Parameters:scope – optional. default: ['email'].
flask_oauthlib.contrib.apps.linkedin()

The OAuth app for LinkedIn API.

Parameters:scope – optional. default: ['r_basicprofile']
flask_oauthlib.contrib.apps.twitter()

The OAuth app for Twitter API.

flask_oauthlib.contrib.apps.weibo()

The OAuth app for weibo.com API.

Parameters:scope – optional. default: ['email']