python - CSRF protection on AJAX authentication in Flask -
python - CSRF protection on AJAX authentication in Flask -
i'd ajaxify both login , signup form on site. i've been using wtforms built-in csrf protetion, project didn't sense worth -- layer of abstraction, , hence frustration, should pretty simple.
so came across this snippet on flask's security section:
@app.before_request def csrf_protect(): if request.method == "post": token = session.pop('_csrf_token', none) if not token or token != request.form.get('_csrf_token'): abort(403) def generate_csrf_token(): if '_csrf_token' not in session: session['_csrf_token'] = some_random_string() homecoming session['_csrf_token'] app.jinja_env.globals['csrf_token'] = generate_csrf_token i understand thought process behind code. in fact, makes perfect sense me (i think). can't see wrong it.
but doesn't work. thing i've changed code replacing pseudofunction some_random_string() phone call os.urandom(24). every request has 403'd far because token , request.form.get('_csrf_token') never same. when print them becomes obvious -- they're different strings, occasionally, , seemingly no underlying reason, 1 or other none or truncated version of output of os.urandom(24). out of sync, i'm not understanding is.
you can convenience of flask-wtf without heaviness, , without rolling own:
from flask_wtf.csrf import csrfprotect then on init, either:
csrfprotect(app) or:
csrf = csrfprotect() def create_app(): app = flask(__name__) csrf.init_app(app) the token available app-wide @ point, including via jinja2:
<form method="post" action="/"> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" /> </form> (via docs)
python ajax flask csrf
Comments
Post a Comment