Search code examples
pythonflaskcsrfplotly-dash

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?

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.


Solution

  • From: https://github.com/plotly/dash/issues/308

    Solution

    Add the following line to exempt dash from csrf token requirements:

    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.
    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.