This part of the documentation covers the interface of Flask OAuth 2.0 Server.
Flask implementation of authlib.oauth2.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.id
else:
user_id = None
client = request.client
tok = Token(
client_id=client.client_id,
user_id=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.
request – HTTP request instance.
grant_user – if granted, it is resource owner. If denied, it is None.
Response
Create a generator function for generating token
value. This
method will create a Bearer Token generator with
authlib.oauth2.rfc6750.BearerToken
.
Configurable settings:
OAUTH2_ACCESS_TOKEN_GENERATOR: Boolean or import string, default is True.
OAUTH2_REFRESH_TOKEN_GENERATOR: Boolean or import string, default is False.
OAUTH2_TOKEN_EXPIRES_IN: Dict or import string, default is None.
By default, it will not generate refresh_token
, which can be turn on by
configure OAUTH2_REFRESH_TOKEN_GENERATOR
.
Here are some examples of the token generator:
OAUTH2_ACCESS_TOKEN_GENERATOR = 'your_project.generators.gen_token'
# and in module `your_project.generators`, you can define:
def gen_token(client, grant_type, user, scope):
# generate token according to these parameters
token = create_random_token()
return f'{client.id}-{user.id}-{token}'
Here is an example of OAUTH2_TOKEN_EXPIRES_IN
:
OAUTH2_TOKEN_EXPIRES_IN = {
'authorization_code': 864000,
'urn:ietf:params:oauth:grant-type:jwt-bearer': 3600,
}
Validate endpoint request and create endpoint response.
name – Endpoint name
request – HTTP request instance.
Response
Validate token request and create token response.
request – HTTP request instance
Validate current HTTP request for authorization page. This page is designed for resource owner to grant or deny the authorization.
Add extra endpoint to authorization server. e.g. RevocationEndpoint:
authorization_server.register_endpoint(RevocationEndpoint)
endpoint_cls – A endpoint class
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)
grant_cls – a grant class.
extensions – extensions for the grant class.
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()
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 HTTPException for OAuth2Error. Developers can re-implement this method to customize the error response.
error – OAuth2Error
HTTPException
A method to acquire current valid token with the given scope.
scopes – a list of scope values
token object
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())
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
Signal when client is authenticated
Signal when token is revoked
Signal when token is authenticated
Warning
We will drop sqla_oauth2
module in version 1.0.
Create an query_client
function that can be used in authorization
server.
session – SQLAlchemy session
client_model – Client model class
Create an save_token
function that can be used in authorization
server.
session – SQLAlchemy session
token_model – Token model class
Create an query_token
function for revocation, introspection
token endpoints.
session – SQLAlchemy session
token_model – Token model class
Create a revocation endpoint class with SQLAlchemy session and token model.
session – SQLAlchemy session
token_model – Token model class
Create an bearer token validator class with SQLAlchemy session and token model.
session – SQLAlchemy session
token_model – Token model class