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 withquery_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)
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 withauthlib.oauth2.rfc6750.BearerToken
. By default, it will not generaterefresh_token
, which can be turn on by configurationOAUTH2_REFRESH_TOKEN_GENERATOR=True
.
-
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_expires_in_generator
(config)¶ 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 bygrant_type
, differentgrant_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 – HTTP request instance
-
register_endpoint
(endpoint_cls)¶ Add extra endpoint to authorization server. e.g. RevocationEndpoint:
authorization_server.register_endpoint(RevocationEndpoint)
- Parameters
endpoint_cls – A endpoint class
-
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.
-
validate_consent_request
(request=None, end_user=None)¶ 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.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() 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.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