簡體   English   中英

燒瓶登錄中基於角色的授權

[英]Role based authorization in flask-login

我需要在現有的 Flask 應用程序中引入基於角色的授權。 因此,例如,我不能僅將當前使用的燒瓶登錄 package 與燒瓶用戶交換。 盡管如此,我必須將對某些端點的訪問限制為“管理員”用戶,而無需重建整個代碼庫。

我想出了一個這樣的裝飾器:

def admin_required(func):
    """
    Modified login_required decorator to restrict access to admin group.
    """

    @wraps(func)
    def decorated_view(*args, **kwargs):
        if current_user.group != 0:        # zero means admin, one and up are other groups
            flash("You don't have permission to access this resource.", "warning")
            return redirect(url_for("main.home"))
        return func(*args, **kwargs)
    return decorated_view

我將它與原始login_required裝飾器一起使用,如下所示:

@app.route("/admin-restricted"):
@login_required
@admin_required
def admin_resource():
    return "Hello admin"

一切都按預期工作,但我有兩個擔憂:

  1. 我的方法安全嗎? 我是否錯過了一些潛在的安全漏洞? 不幸的是,我對 Flask 內部結構了解有限。
  2. 有沒有更簡單/安全/pythonic的方法來做到這一點? 我只是覺得不對勁。

處理基於角色的權限的更常見方法是使用 Flask Principal。

在主應用程序中:

from flask_principal import Principal

# load the extension
principals = Principal(app)

@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    # Set the identity user object
    identity.user = current_user
    # Add the UserNeed to the identity
    if hasattr(current_user, 'employee_id'):
        identity.provides.add(UserNeed(current_user.employee_id))

    # Assuming the User model has a list of roles, update the
    # identity with the roles that the user provides
    if hasattr(current_user, 'position'):
        # for role in current_user.role:
        identity.provides.add(RoleNeed(str(current_user.position)))

   admin_permission = Permission(RoleNeed('admin'))

然后在路線中:

@app.route("/admin-restricted"):
@login_required
@admin_permission.require(http_exception=403)
def admin_resource():
    return "Hello admin"

文檔: https://pythonhosted.org/Flask-Principal/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM