Open In App

CSRF Protection in Flask

Last Updated : 05 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Let’s see how you can manually protect your data using CSRF protection by doing a mini-project in Flask. In this, we will have to create a webpage containing 2 forms using Python one of them is having protection. By creating forms like these we can easily see the results and advantages of using CSRF protection for our application.

What is CSRF?

Cross-Site Request Forgery(CSRF) is a weighty exposure that results from weak gathering administration. If that requests shipped by an application aren’t rare, it’s likely for an aggressor to art a certain request and transmits that to a consumer. If the consumer communicates accompanying the workout request, and gatherings aren’t controlled correctly, an aggressor grant permission within financial means to acquire the gathering similarity of that consumer and complete activity requests on their side.

Solution for Preventing CSRF Attacks

Cross-Site Request Forgery (CSRF) attacks are comparably smooth to diminish. One of the plainest habits to manage this is through the use of CSRF tokens, which are uncommon principles dynamically created by a server-side request and shipped to the customer. Since these principles are rare for each request, and uniformly changeful, it is almost hopeless for a raider to pre-generate the URLs/requests for an attack.

### recreate image

 

Example of CSRF Protection in Flask

Step 1: Create a Virtual environment for our application and install the following packages.

Step 2: Installing Packages.

 pip install flask, flask-wtf

Step 3: You should have to create a folder structure like this. 

 

Step 4: app.py

In Flask, we are having generally 2 ways to create a form one by using FlaskForm and another by creating forms manually. FlaskForm processes the request that already getting CSRF Protection. Csrf requires a secret key by default, it uses the Flask app’s Secret Key. If you like to set up a separate token then you can use WTF_CSRF_SECRET_KEY instead of using a flask app’s secret key. While using FlaskForm, you will have to render the forms CSRF field.n You can disable the CSRF Protection in all views by default, then set WTF_CSRF_CHECK_DEFAULT to False in the app.py file.

Python3




from flask import Flask, render_template, request
from flask_wtf import CSRFProtect
  
app = Flask(__name__)
app.secret_key = b'_53oi3uriq9pifpff;apl'
csrf = CSRFProtect(app)
  
  
@app.route("/protected_form", methods=['GET', 'POST'])
def protected_form():
    if request.method == 'POST':
        name = request.form['Name']
        return (' Hello ' + name + '!!!')
    return render_template('index.html')
  
@app.route("/unprotected_form", methods=['GET', 'POST'])
def unprotected_form():
    if request.method == 'POST':
        name = request.form['Name']
        return (' Hello ' + name + '!!!')
    return render_template('index.html')
  
if __name__ == '__main__':
    app.run(debug=True)


Step 5: templates/index.html 

A simple HTML page is set up for the app to show the unprotected and protected submission of the form. 

HTML




<html>
<head></head>
<body>
<form action="{{ url_for('protected_form') }}" method="POST">
    <label for="Name">Your Name Please ? </label>
    <input type="text" name="Name">
    <input type="hidden" name="csrf_token" value = "{{ csrf_token() }}" /> 
    <button type="submit">Submit</button>
</form>
  
  
<form action="{{ url_for('unprotected_form') }}" method="POST">
    <label for="Name">Your Name Please ? </label>
    <input type="text" name="Name">
    <button type="submit">Submit</button>
</form>
  
</body>
</html>


Step 5: Now run it to see the webpage and perform the practice.

python app.py

Output:

Visit ‘127.0.0.1:5000/protected_form‘ and try submitting both forms and one by one you should get the following outputs. While submitting the first form we applied the token inside the form so that it checks the token if it presents it serves the request else it generates an error.

CSRF Protection in Flask

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads