跳转到主要内容

Dash授权包。

项目描述

Dash授权和登录

文档: https://dash.plotly.com/authentication

许可证:MIT

测试: CircleCI

对于本地测试,创建一个虚拟环境,安装开发需求,并运行单个测试或测试类

python -m venv venv
. venv/bin/activate
pip install -r dev-requirements.txt
python -k ba001

注意,需要Python 3.8或更高版本。

用法

基本认证

要添加基本认证,请将以下内容添加到您的Dash应用程序中

from dash import Dash
from dash_auth import BasicAuth

app = Dash(__name__)
USER_PWD = {
    "username": "password",
    "user2": "useSomethingMoreSecurePlease",
}
BasicAuth(app, USER_PWD)

也可以使用授权Python函数而不是用户名和密码的字典/列表

from dash import Dash
from dash_auth import BasicAuth

def authorization_function(username, password):
    if (username == "hello") and (password == "world"):
        return True
    else:
        return False


app = Dash(__name__)
BasicAuth(app, auth_func = authorization_function)

公开路由

您可以使用add_public_routes实用函数或通过将public_routes参数传递给Auth构造函数来将认证的路由列入白名单。公开路由应遵循Flask的路由语法

from dash import Dash
from dash_auth import BasicAuth, add_public_routes

app = Dash(__name__)
USER_PWD = {
    "username": "password",
    "user2": "useSomethingMoreSecurePlease",
}
BasicAuth(app, USER_PWD, public_routes=["/"])

add_public_routes(app, public_routes=["/user/<user_id>/public"])

注意:如果您在公开路由上使用服务器端回调,则也应使用dash_auth的新public_callback而不是默认的Dash回调。以下是一个多页面Dash应用程序的公开路由和回调示例,该应用程序使用Dash的pages API

app.py

from dash import Dash, html, dcc, page_container
from dash_auth import BasicAuth

app = Dash(__name__, use_pages=True, suppress_callback_exceptions=True)
USER_PWD = {
    "username": "password",
    "user2": "useSomethingMoreSecurePlease",
}
BasicAuth(app, USER_PWD, public_routes=["/", "/user/<user_id>/public"])

app.layout = html.Div(
    [
        html.Div(
            [
                dcc.Link("Home", href="/"),
                dcc.Link("John Doe", href="/user/john_doe/public"),
            ],
            style={"display": "flex", "gap": "1rem", "background": "lightgray", "padding": "0.5rem 1rem"},
        ),
        page_container,
    ],
    style={"display": "flex", "flexDirection": "column"},
)

if __name__ == "__main__":
    app.run_server(debug=True)

pages/home.py

from dash import Input, Output, html, register_page
from dash_auth import public_callback

register_page(__name__, "/")

layout = [
    html.H1("Home Page"),
    html.Button("Click me", id="home-button"),
    html.Div(id="home-contents"),
]

# Note the use of public callback here rather than the default Dash callback
@public_callback(
    Output("home-contents", "children"),
    Input("home-button", "n_clicks"),
)
def home(n_clicks):
    if not n_clicks:
        return "You haven't clicked the button."
    return "You clicked the button {} times".format(n_clicks)

pages/public_user.py

from dash import html, dcc, register_page

register_page(__name__, path_template="/user/<user_id>/public")

def layout(user_id: str):
    return [
        html.H1(f"User {user_id} (public)"),
        dcc.Link("Authenticated user content", href=f"/user/{user_id}/private"),
    ]

pages/private_user.py

from dash import html, register_page

register_page(__name__, path_template="/user/<user_id>/private")

def layout(user_id: str):
    return [
        html.H1(f"User {user_id} (authenticated only)"),
        html.Div("Members-only information"),
    ]

OIDC认证

要添加基于OpenID Connect的认证,您首先需要设置一个OpenID Connect提供程序(IDP)。这通常需要创建

一旦您设置了IDP,您可以按照以下方式将其添加到您的Dash应用程序中

from dash import Dash
from dash_auth import OIDCAuth

app = Dash(__name__)

auth = OIDCAuth(app, secret_key="aStaticSecretKey!")
auth.register_provider(
    "idp",
    token_endpoint_auth_method="client_secret_post",
    # Replace the below values with your own
    # NOTE: Do not hardcode your client secret!
    client_id="<my-client-id>",
    client_secret="<my-client-secret>",
    server_metadata_url="<my-idp-.well-known-configuration>",
)

完成此操作后,连接到您的应用程序将自动重定向到IDP登录页面。

多个OIDC提供程序

对于多个OIDC提供程序,您可以在实例化OIDCAuth后使用register_provider添加新的提供程序。

from dash import Dash, html
from dash_auth import OIDCAuth
from flask import request, redirect, url_for

app = Dash(__name__)

app.layout = html.Div([
    html.Div("Hello world!"),
    html.A("Logout", href="/oidc/logout"),
])

auth = OIDCAuth(
    app,
    secret_key="aStaticSecretKey!",
    # Set the route at which the user will select the IDP they wish to login with
    idp_selection_route="/login",
)
auth.register_provider(
    "IDP 1",
    token_endpoint_auth_method="client_secret_post",
    client_id="<my-client-id>",
    client_secret="<my-client-secret>",
    server_metadata_url="<my-idp-.well-known-configuration>",
)
auth.register_provider(
    "IDP 2",
    token_endpoint_auth_method="client_secret_post",
    client_id="<my-client-id2>",
    client_secret="<my-client-secret2>",
    server_metadata_url="<my-idp2-.well-known-configuration>",
)

@app.server.route("/login", methods=["GET", "POST"])
def login_handler():
    if request.method == "POST":
        idp = request.form.get("idp")
    else:
        idp = request.args.get("idp")

    if idp is not None:
        return redirect(url_for("oidc_login", idp=idp))

    return """<div>
        <form>
            <div>How do you wish to sign in:</div>
            <select name="idp">
                <option value="IDP 1">IDP 1</option>
                <option value="IDP 2">IDP 2</option>
            </select>
            <input type="submit" value="Login">
        </form>
    </div>"""


if __name__ == "__main__":
    app.run_server(debug=True)

基于用户组的权限

dash_auth提供了一个方便的方法来根据用户组来保护应用程序的某些部分。

以下定义了以下实用程序

  • list_groups:返回当前用户的组,如果用户未认证则返回None。
  • check_groups:检查当前用户组是否与提供的组列表匹配。可用的组检查有one_ofall_ofnone_of。如果用户未认证,函数返回None。
  • protected:一个函数装饰器,如果用户未认证或缺少组权限,则修改输出。
  • protected_callback:一个回调,只有当用户认证且具有正确的组权限时才运行。

注意:用户信息存储在会话中,因此请确保您在Flask服务器上定义了一个secret_key来使用此功能。

如果您希望使用基本认证,则需要为单个basicauth用户定义组

from dash_auth import BasicAuth

app = Dash(__name__)
USER_PWD = {
    "username": "password",
    "user2": "useSomethingMoreSecurePlease",
}
BasicAuth(
    app,
    USER_PWD,
    user_groups={"user1": ["group1", "group2"], "user2": ["group2"]},
    secret_key="Test!",
)

# You can also use a function to get user groups
def check_user(username, password):
    if username == "user1" and password == "password":
        return True
    if username == "user2" and password == "useSomethingMoreSecurePlease":
        return True
    return False

def get_user_groups(user):
    if user == "user1":
        return ["group1", "group2"]
    elif user == "user2":
        return ["group2"]
    return []

BasicAuth(
    app,
    auth_func=check_user,
    user_groups=get_user_groups,
    secret_key="Test!",
)

发布历史 发布通知 | RSS源

下载文件

下载适合您平台的应用程序。如果您不确定选择哪一个,请了解有关安装包的更多信息。

源代码分发

dash_auth-2.3.0.tar.gz (17.7 kB 查看哈希值)

上传时间 源代码

构建分发

dash_auth-2.3.0-py3-none-any.whl (14.4 kB 查看哈希值)

上传时间 Python 3

支持者