简体   繁体   English

使用 Dash 的 Flask 框架中的 CSRF 保护

[英]CSRF Protection in a Flask Framework that uses Dash

This question builds upon my previous question about dash integration.这个问题建立在我之前关于破折号集成的问题之上。

Question:题:

When CSRF is activated using the flask_wtf module, how do you also integrate Dash modules without blocking Dash posts due to a lack of csrf tokens?当使用flask_wtf模块激活CSRF 时,如何集成Dash 模块而不会因为缺少csrf 令牌而阻塞Dash 帖子?

MWE: 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)

This returns a 404 error whenever /dash is loaded.每当加载/dash时,都会返回 404 错误。

From: https://github.com/plotly/dash/issues/308来自: https : //github.com/plotly/dash/issues/308

Solution解决方案

Add the following line to exempt dash from csrf token requirements:添加以下行以从 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)

Comments注释

  1. Whether or not this is an acceptable solution is up for debate.这是否是一个可以接受的解决方案还有待商榷。 I am not sure if this opens Dash to injections.我不确定这是否会打开 Dash 进行注射。
  2. I am not aware that there is a way to add csrf tokens to dash but if there is, I will update my answer.我不知道有一种方法可以将 csrf 令牌添加到 dash,但如果有,我会更新我的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM