如何解决保护嵌入在通过MSAL认证的Flask应用中的Dash应用的视图
问题:
我有一个内嵌Dash应用程序的Flask应用程序。我已向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等。
解决方法
我想我有一个非常hacky,非常简单的解决方案。对我来说,用户体验不是问题,我只是需要将未经授权的用户拒之门外。
@server.before_request
def requires_authorisation():
allowed_routes = ['/robots.txt','/login','/callback','/']
if 'profile' not in session and request.path not in allowed_routes:
return redirect('/login')
/login 重定向到我们的登录页面,/callback 会在登录后填充配置文件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。