maxcountryman / flask-seasurf

SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).
http://readthedocs.org/docs/flask-seasurf/
Other
190 stars 49 forks source link

Ability to provide custom error pages for CSRF errors #55

Closed alanhamlett closed 8 years ago

alanhamlett commented 8 years ago

It would be nice to provide custom error page content when CSRF tokens fail to validate.

For example, when someone has disabled sending the Referer header in their browser they are presented with a 403 page on any POST request. We should be able to show a custom 403 page that says their request failed because they are missing the Referer header, so they can change their browser settings instead of just thinking the website is broken.

I'm thinking inside the Flask custom 403 error handler we could call csrf.get_error() which would return one of the error message constants (REASON_NO_REFERER, REASON_BAD_REFERER, ...) or None if the 403 was not triggered by Flask-SeaSurf.

This way a user could say:

@app.errorhandler(403)
def forbidden(e):
    csrf_error = csrf.get_error()
    if csrf_error:
        return render_template('custom_csrf_403.html', error=csrf_error), 403
    else:
        return render_template('generic_app_403.html'), 403

An alternative implementation is for Flask-SeaSurf to raise the HTTPException instead of calling abort(403) which adds the ability to change the exception's description attribute. The app's custom error handler is passed that exception, and could customize the error page with the improved description.

I'm happy to submit a pull request once/if we decide between these two implementations :zap: