Python Flask basicAuth auth是Flask Admin视图所需的装饰器

Python Flask basicAuth auth是Flask Admin视图所需的装饰器,python,flask,flask-admin,Python,Flask,Flask Admin,我目前正在使用Flask制作一个后端应用程序,用于管理基于组织的用户消费的资源 由于我正在使用Flask SQLAlchemy,我决定将Flask Admin用于DB的管理视图,但我在保护视图时遇到了问题 我正试图使用Flask BasicAuth来保护管理员视图,但由于路由是自动生成的,因此我无法向其中添加@basic-auth.required装饰程序。 强制站点使用Flask BasicAuth会阻塞资源端点,因此不是一个好的解决方案 尝试了类似的方法,但无效: from flask im

我目前正在使用Flask制作一个后端应用程序,用于管理基于组织的用户消费的资源

由于我正在使用Flask SQLAlchemy,我决定将Flask Admin用于DB的管理视图,但我在保护视图时遇到了问题

我正试图使用Flask BasicAuth来保护管理员视图,但由于路由是自动生成的,因此我无法向其中添加@basic-auth.required装饰程序。 强制站点使用Flask BasicAuth会阻塞资源端点,因此不是一个好的解决方案

尝试了类似的方法,但无效:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_basicauth import BasicAuth

app = Flask(__name__)
db = SQLAlchemy(app)
basic_auth = BasicAuth(app)
admin = Admin(app)

class Module(db.Model):
  __tablename__='Modules'
  name = db.Column(db.String(30), unique=True, nullable=False)

@basic_auth.required
class AdminView(ModelView):
  pass

admin.add_view(AdminView(Module, db.session))

TL;DR:Flask Admin假设我使用登录和会话管理器。Flask BasicAuth假设我可以手动声明路由。需要在不阻塞资源端点的情况下以某种方式集成它们。

我在实现它时遇到了同样的问题。@basic\u auth.required装饰程序不起作用。相反,我们必须调整flask_admin的几个类,使其与BasicAuth兼容。在参考了几十种资源之后,下面是我如何成功实现它的

我要说的是,我正在使用: Python 3.6.9,Flask==1.1.1,Flask Admin==1.5.4,Flask BasicAuth==0.2.0

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib.sqla import ModelView
from flask_basicauth import BasicAuth
from werkzeug.exceptions import HTTPException

app = Flask(__name__)
db = SQLAlchemy(app)
basic_auth = BasicAuth(app)

class Module(db.Model):
  __tablename__='Modules'
  name = db.Column(db.String(30), unique=True, nullable=False)

"""
The following three classes are inherited from their respective base class,
and are customized, to make flask_admin compatible with BasicAuth.
"""
class AuthException(HTTPException):
    def __init__(self, message):
        super().__init__(message, Response(
            "You could not be authenticated. Please refresh the page.", 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'} ))

class MyModelView(ModelView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException('Not authenticated.')
        else:
            return True
    def inaccessible_callback(self, name, **kwargs):
        return redirect(basic_auth.challenge())

class MyAdminIndexView(AdminIndexView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException('Not authenticated.')
        else:
            return True
    def inaccessible_callback(self, name, **kwargs):
        return redirect(basic_auth.challenge())

admin = Admin(app, index_view=MyAdminIndexView())

admin.add_view(MyModelView(Module, db.session))

在实施过程中,我遇到了同样的问题。@basic\u auth.required装饰程序不起作用。相反,我们必须调整flask_admin的几个类,使其与BasicAuth兼容。在参考了几十种资源之后,下面是我如何成功实现它的

我要说的是,我正在使用: Python 3.6.9,Flask==1.1.1,Flask Admin==1.5.4,Flask BasicAuth==0.2.0

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib.sqla import ModelView
from flask_basicauth import BasicAuth
from werkzeug.exceptions import HTTPException

app = Flask(__name__)
db = SQLAlchemy(app)
basic_auth = BasicAuth(app)

class Module(db.Model):
  __tablename__='Modules'
  name = db.Column(db.String(30), unique=True, nullable=False)

"""
The following three classes are inherited from their respective base class,
and are customized, to make flask_admin compatible with BasicAuth.
"""
class AuthException(HTTPException):
    def __init__(self, message):
        super().__init__(message, Response(
            "You could not be authenticated. Please refresh the page.", 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'} ))

class MyModelView(ModelView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException('Not authenticated.')
        else:
            return True
    def inaccessible_callback(self, name, **kwargs):
        return redirect(basic_auth.challenge())

class MyAdminIndexView(AdminIndexView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException('Not authenticated.')
        else:
            return True
    def inaccessible_callback(self, name, **kwargs):
        return redirect(basic_auth.challenge())

admin = Admin(app, index_view=MyAdminIndexView())

admin.add_view(MyModelView(Module, db.session))
上面说,没有简单的方法可以将它实现到您的管理页面。然而,我找到了一个解决办法。您可能需要修改flask中的一些现有类,使其与basic auth兼容。将这些添加到代码中。仅供参考,您需要从flask导入响应

class ModelView(sqla.ModelView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException('Not authenticated.')
        else:
            return True

    def inaccessible_callback(self, name, **kwargs):
    return redirect(basic_auth.challenge())
from werkzeug.exceptions import HTTPException


class AuthException(HTTPException):
    def __init__(self, message):
        super().__init__(message, Response(
            "You could not be authenticated. Please refresh the page.", 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'}
        ))
然后像这样添加管理视图

admin = Admin(app)
admin.add_view(ModelView(Module, db.session))
上面说,没有简单的方法可以将它实现到您的管理页面。然而,我找到了一个解决办法。您可能需要修改flask中的一些现有类,使其与basic auth兼容。将这些添加到代码中。仅供参考,您需要从flask导入响应

class ModelView(sqla.ModelView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException('Not authenticated.')
        else:
            return True

    def inaccessible_callback(self, name, **kwargs):
    return redirect(basic_auth.challenge())
from werkzeug.exceptions import HTTPException


class AuthException(HTTPException):
    def __init__(self, message):
        super().__init__(message, Response(
            "You could not be authenticated. Please refresh the page.", 401,
            {'WWW-Authenticate': 'Basic realm="Login Required"'}
        ))
然后像这样添加管理视图

admin = Admin(app)
admin.add_view(ModelView(Module, db.session))

如果您了解数据库模型和函数decorator,就可以简单地实现自己的decorator函数,从而达到预期的效果。例如,我有一个白名单装饰功能,用于保护路由的flask应用程序,它检查IP是否存在以及是否来自允许的来源。在这个文件中。我还导入了一个数据库类对象来保存和存储IP数据。如果您了解数据库模型和函数decorator,您可以简单地实现自己的decorator函数,从而达到预期的效果。例如,我有一个白名单装饰功能,用于保护路由的flask应用程序,它检查IP是否存在以及是否来自允许的来源。我还导入了一个数据库类对象来保存和存储IP数据。