Skip to content

Commit

Permalink
Docs for OAauth2-based custom login manager (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
jwag956 committed May 7, 2019
1 parent fd42915 commit 5571773
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions docs/customizing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,76 @@ Celery. The practical way with custom serialization may look like so::
html=msg.html)

.. _Celery: http://www.celeryproject.org/


Authorization with OAuth2
-------------------------

Flask-Security can be set up to co-operate with `Flask-OAuthlib`_,
by implementing a custom request loader that authorizes a user based
either on a `Bearer` token in the HTTP `Authorization` header, or on the
Flask-Security standard authorization logic::

from flask_oauthlib.provider import OAuth2Provider
from flask_security import AnonymousUser
from flask_security.core import (
_user_loader as _flask_security_user_loader,
_request_loader as _flask_security_request_loader)
from flask_security.utils import config_value as security_config_value

oauth = OAuth2Provider(app)

def _request_loader(request):
"""
Load user from OAuth2 Authentication header or using
Flask-Security's request loader.
"""
user = None

if hasattr(request, 'oauth'):
user = request.oauth.user
else:
# Need this try stmt in case oauthlib sometimes throws:
# AttributeError: dict object has no attribute startswith
try:
is_valid, oauth_request = oauth.verify_request(scopes=[])
if is_valid:
user = oauth_request.user
except AttributeError:
pass

if not user:
user = _flask_security_request_loader(request)

return user

def _get_login_manager(app, anonymous_user):
"""Prepare a login manager for Flask-Security to use."""
login_manager = LoginManager()

login_manager.anonymous_user = anonymous_user or AnonymousUser
login_manager.login_view = '{0}.login'.format(
security_config_value('BLUEPRINT_NAME', app=app))
login_manager.user_loader(_flask_security_user_loader)
login_manager.request_loader(_request_loader)

if security_config_value('FLASH_MESSAGES', app=app):
(login_manager.login_message,
login_manager.login_message_category) = (
security_config_value('MSG_LOGIN', app=app))
(login_manager.needs_refresh_message,
login_manager.needs_refresh_message_category) = (
security_config_value('MSG_REFRESH', app=app))
else:
login_manager.login_message = None
login_manager.needs_refresh_message = None

login_manager.init_app(app)
return login_manager

security = Security(
app, user_datastore,
login_manager=_get_login_manager(app, anonymous_user=None))


.. _Flask-OAuthlib: https://flask-oauthlib.readthedocs.io/

0 comments on commit 5571773

Please sign in to comment.