Compare commits
6 Commits
65c3322ecc
...
v0.2.0
Author | SHA1 | Date | |
---|---|---|---|
2425d99492 | |||
be163d35fb | |||
2aaaa9f47f | |||
cb3e313e21 | |||
6f49a180e3 | |||
af8c3a484c |
81
README.rst
81
README.rst
@ -12,6 +12,10 @@ views.
|
||||
|
||||
HTTP Digest Authentication is specified in `RFC 2617`_.
|
||||
|
||||
|
||||
Why HTTP Digest Authentication?
|
||||
-------------------------------
|
||||
|
||||
HTTP Digest Authentication has the advantage that it does not send the
|
||||
actual password to the server, which greatly enhances the security.
|
||||
It uses the challenge-response authentication scheme. The client
|
||||
@ -28,6 +32,46 @@ Flask-Digest-Auth works with Flask-Login_. Log in protection can be
|
||||
separated with the authentication mechanism. You can create protected
|
||||
Flask modules without knowing the actual authentication mechanisms.
|
||||
|
||||
|
||||
Features
|
||||
--------
|
||||
|
||||
There are a couple of Flask HTTP digest authentication
|
||||
implementations. Flask-Digest-Auth has the following features:
|
||||
|
||||
|
||||
Flask-Login Integration
|
||||
#######################
|
||||
|
||||
Flask-Digest-Auth features Flask-Login integration. The views
|
||||
can be totally independent with the actual authentication mechanism.
|
||||
You can write a Flask module that requires log in, without specify
|
||||
the actual authentication mechanism. The application can specify
|
||||
either HTTP Digest Authentication, or the log in forms, as needed.
|
||||
|
||||
|
||||
Session Integration
|
||||
###################
|
||||
|
||||
Flask-Digest-Auth features session integration. The user log in
|
||||
is remembered in the session. The authentication information is not
|
||||
requested again. This is different to the practice of the HTTP Digest
|
||||
Authentication, but is convenient for the log in accounting.
|
||||
|
||||
|
||||
Log Out Support
|
||||
###############
|
||||
|
||||
Flask-Digest-Auth supports log out. The user will be prompted for
|
||||
new username and password.
|
||||
|
||||
|
||||
Log In Bookkeeping
|
||||
##################
|
||||
|
||||
You can register a callback to run when the user logs in.
|
||||
|
||||
|
||||
.. _HTTP Digest Authentication: https://en.wikipedia.org/wiki/Digest_access_authentication
|
||||
.. _RFC 2617: https://www.rfc-editor.org/rfc/rfc2617
|
||||
.. _Flask: https://flask.palletsprojects.com
|
||||
@ -60,6 +104,8 @@ Flask-Digest-Auth Alone
|
||||
|
||||
Flask-Digest-Auth can authenticate the users alone.
|
||||
|
||||
The currently logged-in user can be retrieved at ``g.user``, if any.
|
||||
|
||||
|
||||
Example for Simple Applications with Flask-Digest-Auth Alone
|
||||
------------------------------------------------------------
|
||||
@ -75,6 +121,7 @@ In your ``my_app.py``:
|
||||
... (Configure the Flask application) ...
|
||||
|
||||
auth: DigestAuth = DigestAuth(realm="Admin")
|
||||
auth.init_app(app)
|
||||
|
||||
@auth.register_get_password
|
||||
def get_password_hash(username: str) -> t.Optional[str]:
|
||||
@ -87,7 +134,7 @@ In your ``my_app.py``:
|
||||
@app.get("/admin")
|
||||
@auth.login_required
|
||||
def admin():
|
||||
... (Process the view) ...
|
||||
return f"Hello, {g.user.username}!"
|
||||
|
||||
@app.post("/logout")
|
||||
@auth.login_required
|
||||
@ -113,6 +160,7 @@ In your ``my_app/__init__.py``:
|
||||
... (Configure the Flask application) ...
|
||||
|
||||
auth.realm = app.config["REALM"]
|
||||
auth.init_app(app)
|
||||
|
||||
@auth.register_get_password
|
||||
def get_password_hash(username: str) -> t.Optional[str]:
|
||||
@ -136,7 +184,7 @@ In your ``my_app/views.py``:
|
||||
@bp.get("/admin")
|
||||
@auth.login_required
|
||||
def admin():
|
||||
... (Process the view) ...
|
||||
return f"Hello, {g.user.username}!"
|
||||
|
||||
@app.post("/logout")
|
||||
@auth.login_required
|
||||
@ -156,6 +204,12 @@ module that requires log in, without specifying the authentication
|
||||
mechanism. The Flask application can specify the actual
|
||||
authentication mechanism as it sees fit.
|
||||
|
||||
``login_manager.init_app(app)`` must be called before
|
||||
``auth.init_app(app)``.
|
||||
|
||||
The currently logged-in user can be retrieved at
|
||||
``flask_login.current_user``, if any.
|
||||
|
||||
|
||||
Example for Simple Applications with Flask-Login Integration
|
||||
------------------------------------------------------------
|
||||
@ -164,14 +218,14 @@ In your ``my_app.py``:
|
||||
|
||||
::
|
||||
|
||||
import flask_login
|
||||
from flask import Flask, request, redirect
|
||||
from flask_digest_auth import DigestAuth
|
||||
from flask_login import LoginManager
|
||||
|
||||
app: flask = Flask(__name__)
|
||||
... (Configure the Flask application) ...
|
||||
|
||||
login_manager: LoginManager = LoginManager()
|
||||
login_manager: flask_login.LoginManager = flask_login.LoginManager()
|
||||
login_manager.init_app(app)
|
||||
|
||||
@login_manager.user_loader
|
||||
@ -186,9 +240,9 @@ In your ``my_app.py``:
|
||||
... (Load the password hash) ...
|
||||
|
||||
@app.get("/admin")
|
||||
@login_manager.login_required
|
||||
@flask_login.login_required
|
||||
def admin():
|
||||
... (Process the view) ...
|
||||
return f"Hello, {flask_login.current_user.get_id()}!"
|
||||
|
||||
@app.post("/logout")
|
||||
@flask_login.login_required
|
||||
@ -244,7 +298,7 @@ In your ``my_app/views.py``:
|
||||
@bp.get("/admin")
|
||||
@flask_login.login_required
|
||||
def admin():
|
||||
... (Process the view) ...
|
||||
return f"Hello, {flask_login.current_user.get_id()}!"
|
||||
|
||||
@app.post("/logout")
|
||||
@flask_login.login_required
|
||||
@ -288,6 +342,19 @@ the next browser automatic authentication to fail, forcing the browser
|
||||
to ask the user for the username and password again.
|
||||
|
||||
|
||||
Log In Bookkeeping
|
||||
=================#
|
||||
|
||||
You can register a callback to run when the user logs in, for ex.,
|
||||
logging the log in event, adding the log in counter, etc.
|
||||
|
||||
::
|
||||
|
||||
@auth.register_on_login
|
||||
def on_login(user: User) -> None:
|
||||
user.visits = user.visits + 1
|
||||
|
||||
|
||||
Writing Tests
|
||||
=============
|
||||
|
||||
|
@ -17,7 +17,7 @@
|
||||
|
||||
[metadata]
|
||||
name = flask-digest-auth
|
||||
version = 0.1.1
|
||||
version = 0.2.0
|
||||
author = imacat
|
||||
author_email = imacat@mail.imacat.idv.tw
|
||||
description = The Flask HTTP Digest Authentication project.
|
||||
|
@ -27,8 +27,7 @@ from functools import wraps
|
||||
from random import random
|
||||
from secrets import token_urlsafe
|
||||
|
||||
from flask import g, request, Response, session, abort, Flask, Request, \
|
||||
current_app
|
||||
from flask import g, request, Response, session, abort, Flask, Request
|
||||
from itsdangerous import URLSafeTimedSerializer, BadData
|
||||
from werkzeug.datastructures import Authorization
|
||||
|
||||
@ -36,6 +35,50 @@ from flask_digest_auth.algo import calc_response
|
||||
from flask_digest_auth.exception import UnauthorizedException
|
||||
|
||||
|
||||
class BasePasswordHashGetter:
|
||||
"""The base password hash getter."""
|
||||
|
||||
@staticmethod
|
||||
def __call__(username: str) -> t.Optional[str]:
|
||||
"""Returns the password hash of a user.
|
||||
|
||||
:param username: The username.
|
||||
:return: The password hash, or None if the user does not exist.
|
||||
:raise UnboundLocalError: When the password hash getter function is
|
||||
not registered yet.
|
||||
"""
|
||||
raise UnboundLocalError("The function to return the password hash"
|
||||
" was not registered yet.")
|
||||
|
||||
|
||||
class BaseUserGetter:
|
||||
"""The base user getter."""
|
||||
|
||||
@staticmethod
|
||||
def __call__(username: str) -> t.Optional[t.Any]:
|
||||
"""Returns a user.
|
||||
|
||||
:param username: The username.
|
||||
:return: The user, or None if the user does not exist.
|
||||
:raise UnboundLocalError: When the user getter function is not
|
||||
registered yet.
|
||||
"""
|
||||
raise UnboundLocalError("The function to return the user"
|
||||
" was not registered yet.")
|
||||
|
||||
|
||||
class BaseOnLogInCallback:
|
||||
"""The base callback when the user logs in."""
|
||||
|
||||
@staticmethod
|
||||
def __call__(user: t.Any) -> None:
|
||||
"""Runs the callback when the user logs in.
|
||||
|
||||
:param user: The logged-in user.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
|
||||
class DigestAuth:
|
||||
"""The HTTP digest authentication."""
|
||||
|
||||
@ -52,9 +95,11 @@ class DigestAuth:
|
||||
self.use_opaque: bool = True
|
||||
self.domain: t.List[str] = []
|
||||
self.qop: t.List[str] = ["auth", "auth-int"]
|
||||
self.__get_password_hash: t.Callable[[str], t.Optional[str]] \
|
||||
= lambda x: None
|
||||
self.__get_user: t.Callable[[str], t.Optional] = lambda x: None
|
||||
self.app: t.Optional[Flask] = None
|
||||
self.__get_password_hash: BasePasswordHashGetter \
|
||||
= BasePasswordHashGetter()
|
||||
self.__get_user: BaseUserGetter = BaseUserGetter()
|
||||
self.__on_login: BaseOnLogInCallback = BaseOnLogInCallback()
|
||||
|
||||
def login_required(self, view) -> t.Callable:
|
||||
"""The view decorator for HTTP digest authentication.
|
||||
@ -93,7 +138,9 @@ class DigestAuth:
|
||||
"Not an HTTP digest authorization")
|
||||
self.authenticate(state)
|
||||
session["user"] = authorization.username
|
||||
g.user = self.__get_user(authorization.username)
|
||||
user = self.__get_user(authorization.username)
|
||||
g.user = user
|
||||
self.__on_login(user)
|
||||
return view(*args, **kwargs)
|
||||
except UnauthorizedException as e:
|
||||
if len(e.args) > 0:
|
||||
@ -127,8 +174,8 @@ class DigestAuth:
|
||||
except BadData:
|
||||
raise UnauthorizedException("Invalid opaque")
|
||||
state.opaque = authorization.opaque
|
||||
password_hash: t.Optional[str] = self.__get_password_hash(
|
||||
authorization.username)
|
||||
password_hash: t.Optional[str] \
|
||||
= self.__get_password_hash(authorization.username)
|
||||
if password_hash is None:
|
||||
raise UnauthorizedException(
|
||||
f"No such user \"{authorization.username}\"")
|
||||
@ -187,7 +234,20 @@ class DigestAuth:
|
||||
hash, or None if the user does not exist.
|
||||
:return: None.
|
||||
"""
|
||||
self.__get_password_hash = func
|
||||
|
||||
class PasswordHashGetter(BasePasswordHashGetter):
|
||||
"""The base password hash getter."""
|
||||
|
||||
@staticmethod
|
||||
def __call__(username: str) -> t.Optional[str]:
|
||||
"""Returns the password hash of a user.
|
||||
|
||||
:param username: The username.
|
||||
:return: The password hash, or None if the user does not exist.
|
||||
"""
|
||||
return func(username)
|
||||
|
||||
self.__get_password_hash = PasswordHashGetter()
|
||||
|
||||
def register_get_user(self, func: t.Callable[[str], t.Optional[t.Any]])\
|
||||
-> None:
|
||||
@ -197,7 +257,41 @@ class DigestAuth:
|
||||
or None if the user does not exist.
|
||||
:return: None.
|
||||
"""
|
||||
self.__get_user = func
|
||||
|
||||
class UserGetter(BaseUserGetter):
|
||||
"""The user getter."""
|
||||
|
||||
@staticmethod
|
||||
def __call__(username: str) -> t.Optional[t.Any]:
|
||||
"""Returns a user.
|
||||
|
||||
:param username: The username.
|
||||
:return: The user, or None if the user does not exist.
|
||||
"""
|
||||
return func(username)
|
||||
|
||||
self.__get_user = UserGetter()
|
||||
|
||||
def register_on_login(self, func: t.Callable[[t.Any], None]) -> None:
|
||||
"""Registers the callback when the user logs in.
|
||||
|
||||
:param func: The callback given the logged-in user.
|
||||
:return: None.
|
||||
"""
|
||||
|
||||
class OnLogInCallback:
|
||||
"""The callback when the user logs in."""
|
||||
|
||||
@staticmethod
|
||||
def __call__(user: t.Any) -> None:
|
||||
"""Runs the callback when the user logs in.
|
||||
|
||||
:param user: The logged-in user.
|
||||
:return: None.
|
||||
"""
|
||||
func(user)
|
||||
|
||||
self.__on_login = OnLogInCallback()
|
||||
|
||||
def init_app(self, app: Flask) -> None:
|
||||
"""Initializes the Flask application.
|
||||
@ -205,13 +299,12 @@ class DigestAuth:
|
||||
:param app: The Flask application.
|
||||
:return: None.
|
||||
"""
|
||||
app.digest_auth = self
|
||||
self.app = app
|
||||
|
||||
try:
|
||||
if hasattr(app, "login_manager"):
|
||||
from flask_login import LoginManager, login_user
|
||||
|
||||
if not hasattr(app, "login_manager"):
|
||||
raise AttributeError(
|
||||
"Please run the Flask-Login init-app() first")
|
||||
login_manager: LoginManager = getattr(app, "login_manager")
|
||||
|
||||
@login_manager.unauthorized_handler
|
||||
@ -246,18 +339,14 @@ class DigestAuth:
|
||||
user = login_manager.user_callback(
|
||||
authorization.username)
|
||||
login_user(user)
|
||||
self.__on_login(user)
|
||||
return user
|
||||
except UnauthorizedException as e:
|
||||
if str(e) != "":
|
||||
app.logger.warning(str(e))
|
||||
return None
|
||||
|
||||
except ModuleNotFoundError:
|
||||
raise ModuleNotFoundError(
|
||||
"init_app() is only for Flask-Login integration")
|
||||
|
||||
@staticmethod
|
||||
def logout() -> None:
|
||||
def logout(self) -> None:
|
||||
"""Logs out the user.
|
||||
This actually causes the next authentication to fail, which forces
|
||||
the browser to ask the user for the username and password again.
|
||||
@ -267,7 +356,7 @@ class DigestAuth:
|
||||
if "user" in session:
|
||||
del session["user"]
|
||||
try:
|
||||
if hasattr(current_app, "login_manager"):
|
||||
if hasattr(self.app, "login_manager"):
|
||||
from flask_login import logout_user
|
||||
logout_user()
|
||||
except ModuleNotFoundError:
|
||||
|
@ -20,7 +20,6 @@
|
||||
"""
|
||||
import typing as t
|
||||
from secrets import token_urlsafe
|
||||
from types import SimpleNamespace
|
||||
|
||||
from flask import Response, Flask, g, redirect, request
|
||||
from flask_testing import TestCase
|
||||
@ -33,6 +32,20 @@ _USERNAME: str = "Mufasa"
|
||||
_PASSWORD: str = "Circle Of Life"
|
||||
|
||||
|
||||
class User:
|
||||
"""A dummy user"""
|
||||
|
||||
def __init__(self, username: str, password_hash: str):
|
||||
"""Constructs a dummy user.
|
||||
|
||||
:param username: The username.
|
||||
:param password_hash: The password hash.
|
||||
"""
|
||||
self.username: str = username
|
||||
self.password_hash: str = password_hash
|
||||
self.visits: int = 0
|
||||
|
||||
|
||||
class AuthenticationTestCase(TestCase):
|
||||
"""The test case for the HTTP digest authentication."""
|
||||
|
||||
@ -49,8 +62,10 @@ class AuthenticationTestCase(TestCase):
|
||||
app.test_client_class = Client
|
||||
|
||||
auth: DigestAuth = DigestAuth(realm=_REALM)
|
||||
user_db: t.Dict[str, str] \
|
||||
= {_USERNAME: make_password_hash(_REALM, _USERNAME, _PASSWORD)}
|
||||
auth.init_app(app)
|
||||
user_db: t.Dict[str, User] \
|
||||
= {_USERNAME: User(
|
||||
_USERNAME, make_password_hash(_REALM, _USERNAME, _PASSWORD))}
|
||||
|
||||
@auth.register_get_password
|
||||
def get_password_hash(username: str) -> t.Optional[str]:
|
||||
@ -59,7 +74,8 @@ class AuthenticationTestCase(TestCase):
|
||||
:param username: The username.
|
||||
:return: The password hash, or None if the user does not exist.
|
||||
"""
|
||||
return user_db[username] if username in user_db else None
|
||||
return user_db[username].password_hash if username in user_db \
|
||||
else None
|
||||
|
||||
@auth.register_get_user
|
||||
def get_user(username: str) -> t.Optional[t.Any]:
|
||||
@ -68,8 +84,16 @@ class AuthenticationTestCase(TestCase):
|
||||
:param username: The username.
|
||||
:return: The user, or None if the user does not exist.
|
||||
"""
|
||||
return SimpleNamespace(username=username) if username in user_db \
|
||||
else None
|
||||
return user_db[username] if username in user_db else None
|
||||
|
||||
@auth.register_on_login
|
||||
def on_login(user: User):
|
||||
"""The callback when the user logs in.
|
||||
|
||||
:param user: The logged-in user.
|
||||
:return: None.
|
||||
"""
|
||||
user.visits = user.visits + 1
|
||||
|
||||
@app.get("/admin-1/auth", endpoint="admin-1")
|
||||
@auth.login_required
|
||||
@ -117,6 +141,7 @@ class AuthenticationTestCase(TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.data.decode("UTF-8"),
|
||||
f"Hello, {_USERNAME}! #2")
|
||||
self.assertEqual(g.user.visits, 1)
|
||||
|
||||
def test_stale_opaque(self) -> None:
|
||||
"""Tests the stale and opaque value.
|
||||
@ -193,3 +218,4 @@ class AuthenticationTestCase(TestCase):
|
||||
|
||||
response = self.client.get(admin_uri)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(g.user.visits, 2)
|
||||
|
@ -21,6 +21,7 @@
|
||||
import typing as t
|
||||
from secrets import token_urlsafe
|
||||
|
||||
import flask_login
|
||||
from flask import Response, Flask, g, redirect, request
|
||||
from flask_testing import TestCase
|
||||
from werkzeug.datastructures import WWWAuthenticate, Authorization
|
||||
@ -35,12 +36,15 @@ _PASSWORD: str = "Circle Of Life"
|
||||
class User:
|
||||
"""A dummy user."""
|
||||
|
||||
def __init__(self, username: str):
|
||||
def __init__(self, username: str, password_hash: str):
|
||||
"""Constructs a dummy user.
|
||||
|
||||
:param username: The username.
|
||||
:param password_hash: The password hash.
|
||||
"""
|
||||
self.username: str = username
|
||||
self.password_hash: str = password_hash
|
||||
self.visits: int = 0
|
||||
self.is_authenticated: bool = True
|
||||
self.is_active: bool = True
|
||||
self.is_anonymous: bool = False
|
||||
@ -82,8 +86,9 @@ class FlaskLoginTestCase(TestCase):
|
||||
auth: DigestAuth = DigestAuth(realm=_REALM)
|
||||
auth.init_app(app)
|
||||
|
||||
user_db: t.Dict[str, str] \
|
||||
= {_USERNAME: make_password_hash(_REALM, _USERNAME, _PASSWORD)}
|
||||
user_db: t.Dict[str, User] \
|
||||
= {_USERNAME: User(
|
||||
_USERNAME, make_password_hash(_REALM, _USERNAME, _PASSWORD))}
|
||||
|
||||
@auth.register_get_password
|
||||
def get_password_hash(username: str) -> t.Optional[str]:
|
||||
@ -92,7 +97,17 @@ class FlaskLoginTestCase(TestCase):
|
||||
:param username: The username.
|
||||
:return: The password hash, or None if the user does not exist.
|
||||
"""
|
||||
return user_db[username] if username in user_db else None
|
||||
return user_db[username].password_hash if username in user_db \
|
||||
else None
|
||||
|
||||
@auth.register_on_login
|
||||
def on_login(user: User):
|
||||
"""The callback when the user logs in.
|
||||
|
||||
:param user: The logged-in user.
|
||||
:return: None.
|
||||
"""
|
||||
user.visits = user.visits + 1
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(user_id: str) -> t.Optional[User]:
|
||||
@ -101,7 +116,7 @@ class FlaskLoginTestCase(TestCase):
|
||||
:param user_id: The username.
|
||||
:return: The user, or None if the user does not exist.
|
||||
"""
|
||||
return User(user_id) if user_id in user_db else None
|
||||
return user_db[user_id] if user_id in user_db else None
|
||||
|
||||
@app.get("/admin-1/auth", endpoint="admin-1")
|
||||
@flask_login.login_required
|
||||
@ -110,7 +125,7 @@ class FlaskLoginTestCase(TestCase):
|
||||
|
||||
:return: The response.
|
||||
"""
|
||||
return f"Hello, {flask_login.current_user.username}! #1"
|
||||
return f"Hello, {flask_login.current_user.get_id()}! #1"
|
||||
|
||||
@app.get("/admin-2/auth", endpoint="admin-2")
|
||||
@flask_login.login_required
|
||||
@ -119,7 +134,7 @@ class FlaskLoginTestCase(TestCase):
|
||||
|
||||
:return: The response.
|
||||
"""
|
||||
return f"Hello, {flask_login.current_user.username}! #2"
|
||||
return f"Hello, {flask_login.current_user.get_id()}! #2"
|
||||
|
||||
@app.post("/logout", endpoint="logout")
|
||||
@flask_login.login_required
|
||||
@ -152,6 +167,7 @@ class FlaskLoginTestCase(TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.data.decode("UTF-8"),
|
||||
f"Hello, {_USERNAME}! #2")
|
||||
self.assertEqual(flask_login.current_user.visits, 1)
|
||||
|
||||
def test_stale_opaque(self) -> None:
|
||||
"""Tests the stale and opaque value.
|
||||
@ -237,3 +253,4 @@ class FlaskLoginTestCase(TestCase):
|
||||
|
||||
response = self.client.get(admin_uri)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(flask_login.current_user.visits, 2)
|
||||
|
Reference in New Issue
Block a user