【问题标题】:How to hold Plotly dash app behind protected route如何将 Plotly dash 应用程序放在受保护的路线后面
【发布时间】:2019-12-28 23:21:36
【问题描述】:

我有一个 plotly dash 应用程序,我想将它放在受 JWT 保护的路线后面。我的最终目标是将其包含在单独路线上的 iframe 中,但我只希望用户能够获得 dash 应用程序的 html,如果他们有访问令牌。

我已重试在获取请求中返回应用程序本身。

应用程序.py

import dash
from flask import Flask, jsonify, request
from flask_jwt_extended import (
    JWTManager, jwt_required, create_access_token,
    get_jwt_identity
)

server = Flask(__name__)

server.config['JWT_SECRET_KEY'] = 'super-secret'  # Change this!
jwt = JWTManager(server)

@server.route('/login', methods=['POST'])
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    if username != 'test' or password != 'test':
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token), 200

@server.route('/')
@jwt_required
def index():
    return 'Hello world flask app'

app = dash.Dash(
   __name__,
   server=server,
   routes_pathname_prefix='/'
)

app.config.suppress_callback_exceptions = True

索引.py

from app import app
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
from combination_1 import Combination
import callbacks

app.layout = html.Div([
   dcc.Location(id='url', refresh=False),
   html.Div(id="root_div")

])

@app.callback(
   Output('root_div', 'children'),
   [Input('url', 'pathname')]
)
def attatch_graphs(pathname):
   return Combination(comb_id='comb_1').return_div()

if __name__ == '__main__':
   app.run_server()

【问题讨论】:

    标签: python flask plotly-dash flask-jwt-extended


    【解决方案1】:

    我将分享一些我在研究这个问题时发现的资源:

    1. Dash 提供了一个library named dash-auth,您可以使用pip install dash-auth 安装它
    2. 安装库后,您将能够使用import dash_auth,并且您会注意到HTTP Basic Auth、OAuth 和“PlotlyAuth”的子模块。根据from dash_auth.plotly_auth import deprecation_notice 中的文字,“PlotlyAuth”已被弃用
    3. 此模块的源代码似乎是https://github.com/plotly/dash-auth
    4. 文档可在https://dash.plotly.com/authentication 获得,促销页面可在https://plotly.com/dash/authentication/
    5. 推测,JWT 可以使用 Flask 的Response.set_cookie 进行集成。 Here are details about that approach,注意作者使用rep.set_cookie('custom-auth-session', username)
    6. Github 上有一个使用Dash, Flask, and Flask-Login 的示例。此配置也存在于separate StackOverflow question 中。但是,这个库doesn't supports JWT。您或许可以使用 Flask-JWT-Extended 库实现类似的架构。

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 1970-01-01
      • 2020-08-04
      • 2020-09-04
      • 2015-01-25
      • 2020-04-22
      • 2020-01-28
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多