【问题标题】:How to secure Flask-Admin if my only user is going to be the Admin?如果我唯一的用户将成为管理员,如何保护 Flask-Admin?
【发布时间】:2017-07-25 10:37:50
【问题描述】:

我在网上看到了很多解决方案,但它们都解决了允许外部用户创建帐户的更复杂的应用程序。在我的情况下,唯一的用户将是管理员。如何有效地保护 Flask-Admin 创建的 /admin 路由?

【问题讨论】:

    标签: flask flask-admin flask-security


    【解决方案1】:

    您可以为此使用Flask-Login。如果用户尚未登录,我通常会向 AdminIndexView 类添加一个路由来处理登录。否则将显示默认管理页面。

    from flask import Flask
    from flask_login import LoginManager
    from flask_admin import Admin
    
    
    app = Flask(__name__)
    
    login_manager = LoginManager(app)
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'admin.login'
    
    admin = Admin(app, index_view=MyIndexView())
    

    MyAdminView 的定义可以是这样的:

    from flask_admin import AdminIndexView, expose, helpers
    
    
    class FlaskyAdminIndexView(AdminIndexView):
    
        @expose('/')
        def index(self):
            if not login.current_user.is_authenticated:
                return redirect(url_for('.login'))
            return super(MyAdminIndexView, self).index()
    
        @expose('/login', methods=['GET', 'POST'])
        def login(self):
            form = LoginForm(request.form)
            if helpers.validate_form_on_submit(form):
                user = form.get_user()
                if user is not None and user.verify_password(form.password.data):
                    login.login_user(user)
                else:
                    flash('Invalid username or password.')
            if login.current_user.is_authenticated:
                return redirect(url_for('.index'))
            self._template_args['form'] = form
            return super(MyAdminIndexView, self).index()
    
        @expose('/logout')
        @login_required
        def logout(self):
            login.logout_user()
            return redirect(url_for('.login'))
    

    这在 Flask-Admin 界面中不显眼地集成了 Flask-Login。您仍然需要像Flask-Login documentation 中所述那样实现用户和密码验证。

    编辑

    为防止未经授权访问您的管理路由,为每个视图创建一个 ModelView 类,并使用以下代码添加一个函数 is_accessible()

    def is_accessible(self):
        if (not login.current_user.is_active or not
                login.current_user.is_authenticated):
            return False
        return True
    

    【讨论】:

    • 好东西,但 FlaskyAdminIndexView、MyAdminIndexView 和 MyIndexView 有什么区别?
    猜你喜欢
    • 2018-01-07
    • 2020-06-08
    • 2020-04-07
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多