【发布时间】:2021-01-24 01:05:33
【问题描述】:
问题:
我有一个嵌入了 Dash 应用程序的 Flask 应用程序。我向烧瓶应用程序添加了 MSAL 身份验证,但我仍然可以直接转到 local_host:5000/dash 并在不登录的情况下查看我的仪表板。我的目标是保护该仪表板。
对于我的身份验证过程,我引用了https://github.com/Azure-Samples/ms-identity-python-webapp 相当沉重。该方法是将尚未登录的用户重定向回登录屏幕,而不是允许他们进入需要身份验证的屏幕,如下所示:
@app.route("/")
def index():
if not session.get("user"):
return redirect(url_for("login"))
return render_template('index.html', user=session["user"], version=msal.__version__)
@app.route("/login")
def login():
session["state"] = str(uuid.uuid4())
# Technically we could use empty list [] as scopes to do just sign in,
# here we choose to also collect end user consent upfront
auth_url = _build_auth_url(scopes=app_config.SCOPE, state=session["state"])
return render_template("login.html", auth_url=auth_url, version=msal.__version__)
我需要对存储库进行的唯一真正更改是添加以下内容到app.py 文件:
import dash
import dash_html_components as html
dashapp = dash.Dash(__name__, server=app, url_base_pathname='/dash/')
dashapp.layout = html.Div([html.H1('Hi there')])
添加后,我们就有了最小的示例。不幸的是,如前所述,我可以联系到local_host:5000/dash。我希望该 URL 存在,但我希望它受到身份验证的保护。
我的尝试:
我尝试为仪表板制作路线:
@app.route("/dash")
def dashboard():
if not session.get("user"):
return redirect(url_for("login"))
return <*NOT SURE*>
我不能 100% 确定我会在这里返回什么。我尝试了一些类似redirect("\dash") 的方法,但这没关系,因为这条路线永远不会被调用。它不会覆盖 Dash url 基本路径名。
我看到其他人建议使用_protect_dashviews 方法:
from flask_login import login_required
def _protect_dashviews(dashapp):
for view_func in dashapp.server.view_functions:
url_base_pathname = dashapp.config.requests_pathname_prefix
if url_base_pathname is None:
url_base_pathname = '/'
if view_func.startswith(url_base_pathname):
dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func])
_protect_dashviews(dashapp)
这确实使我无法访问/dash URL,但它有一个错误,因为 login_required 未连接到我的身份验证过程。据我所知,它旨在与同一个包中的 LoginManager 一起使用。也许有办法让它与我的身份验证一起使用,但我找不到它。
我已经花了几天时间,所以任何想法都将不胜感激!我愿意更改我的身份验证过程(尽管它需要使用 MSAL)、重组、禁用或覆盖 Dash url 等。任何可能的方法都对我有用。
【问题讨论】:
标签: python authentication flask plotly-dash msal