Flask error after adding csrf protection - Python

564 Views Asked by At

I got the following sonar issue under security hotspots:

enter image description here

Sonar recommended the following fix: enter image description here

So I added the following code:

from flask_wtf.csrf import CSRFProtect
...
app = Flask(__name__)  # unchanged
app.config['SECRET_KEY'] = os.urandom(32) # added because "RuntimeError: A secret key is required to use CSRF."
csrf = CSRFProtect()
csrf.init_app(app)
app.register_blueprint(blueprint)  # unchanged

Now I'm getting a Flask error in my code:

INFO:flask_wtf.csrf:The CSRF token is missing.
ERROR:main:Exception on /my_api/getData [POST]
.
.
.
Traceback (most recent call last):
  File "C:\Users\tempuser\Documents\Git\my-api\venv_py38\lib\site-packages\flask\app.py", line 1541, in finalize_request
    response = self.process_response(response)
  File "C:\Users\tempuser\Documents\Git\my-api\venv_py38\lib\site-packages\flask\app.py", line 1885, in process_response
    response = self.ensure_sync(func)(response)
  File "C:\Users\tempuser\Documents\Git\my-api\venv_py38\lib\site-packages\flask_prometheus_metrics\metrics.py", line 40, in after_request
    request_latency = time.time() - request._prometheus_metrics_request_start_time
AttributeError: 'Request' object has no attribute '_prometheus_metrics_request_start_time'

I'm not sure why other dependencies are failing. Please help!

1

There are 1 best solutions below

3
On

I guess you need to add crsf token into your client side. If you're enabling crsf - every request to your backend must include crsf token

For example:

<form method="POST">
    {{ form.csrf_token }}
    <button type="submit">Sumbit</button>
</form>