CSRF protection on AJAX authentication in Flask
You can get the convenience of flask-wtf
without all the heaviness, and without rolling your 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 will then be available app-wide at any point, including via jinja2
:
<form method="post" action="/"> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" /></form>
(via the docs)
I think your problem is os.urandom function. The result of this function can contains symbols which not will parse properly in html. So when you insert csrf_token in html and don't do any escaping, you have the described problem.
How to fix.Try to escape csrf_token in html (see docs) or use another approach for generating csrf token. For example using uuid:
import uuid...def generate_random_string(): return str(uuid.uuid4())...