【问题标题】:CSRF Protection in a Flask Framework that uses Dash使用 Dash 的 Flask 框架中的 CSRF 保护
【发布时间】:2020-04-15 17:56:23
【问题描述】:

这个问题建立在我关于 dash 集成的 previous question 之上。

问题:

当使用flask_wtf 模块激活 CSRF 时,如何在不因缺少 csrf 令牌而阻止 Dash 帖子的情况下集成 Dash 模块?

MWE:

from flask import Flask, request, render template
from flask_wtf.csrf import CSRFProtect
from dash import Dash
from dash.dependencies import Input, Output


app = Flask(__name__)

csrf = CSRFProtect(app)

app.config['SECRET_KEY'] = 'somethignrandom'

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

dapp.layout = layoutfunction # this is left for your imagination

@app.route('/', methods=['GET','POST'])
def helloworld():
    return render_template('index.html') 

@app.route('/dash')
def dashing():
    dapp.layout = layoutfunction

if __name__ == '__main__':
    app.run(debug=True)

每当加载 /dash 时都会返回 404 错误。

【问题讨论】:

    标签: python flask csrf plotly-dash


    【解决方案1】:

    发件人:https://github.com/plotly/dash/issues/308

    解决方案

    添加以下行以免除 dash 的 csrf 令牌要求:

    from flask import Flask, request, render template
    from flask_wtf.csrf import CSRFProtect
    from dash import Dash
    from dash.dependencies import Input, Output
    
    app = Flask(__name__)
    
    csrf = CSRFProtect(app)
    
    app.config['SECRET_KEY'] = 'somethignrandom'
    
    ########## ADD THIS LINE
    
    csrf._exempt_views.add('dash.dash.dispatch')
    
    ##########
    
    
    dapp = Dash(__name__, server=app, routes_pathname_prefix='/dash/')
    
    dapp.layout = layoutfunction # this is left for your imagination
    
    @app.route('/', methods=['GET','POST'])
    def helloworld():
        return render_template('index.html') 
    
    
    @app.route('/dash')
    def dashing():
        dapp.layout = layoutfunction
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    评论

    1. 这是否是一个可接受的解决方案还有待商榷。我不确定这是否会打开 Dash 进行注射。
    2. 我不知道有办法将 csrf 令牌添加到 dash,但如果有,我会更新我的答案。

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 2019-04-30
      • 2013-05-24
      • 2020-09-26
      • 2017-08-17
      • 2014-12-19
      • 2014-02-25
      • 2015-10-31
      • 2014-03-15
      相关资源
      最近更新 更多