0

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!

Nitesh
  • 180
  • 1
  • 11

1 Answers1

1

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>
imDayWit
  • 11
  • 2
  • The python service/API is used by non-browser based apps so I am testing through postman. I added `X-CSRF-TOKEN=secretkey` header to postman and also changed `app.config['SECRET_KEY'] ="secretkey"` in the code but still getting the same error. Am I doing anything wrong? – Nitesh Apr 14 '23 at 12:22
  • then create additional GET request like that: ``` @app.route('/my_api/get_token', methods=['GET']) def get_token(): csrf_token = generate_csrf() return jsonify({'csrf_token': csrf_token}) ``` Firstly you're gonna send get request to get csrf token and after that you're gonna paste it in your POST request: ``` 'csrf_token': csrf_token ``` – imDayWit Apr 14 '23 at 15:04
  • Hey thanks for the explanation. I couldn't get this working so I exempted all the blueprints and routes with `csrf.exempt()` method ¯\\_(ツ)_/¯ – Nitesh Apr 18 '23 at 14:23