Bird
Raised Fist0
Flaskframework~10 mins

CSRF protection concept in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - CSRF protection concept
User visits form page
↓
Server generates CSRF token
↓
Token included in form as hidden field
↓
User submits form with token
↓
Server checks token validity
↓
Process form
↓
Response
This flow shows how a CSRF token is created, sent with a form, and verified on submission to protect against unauthorized requests.
Execution Sample
Flask
from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

csrf = CSRFProtect(app)

class MyForm(FlaskForm):
    name = StringField('Name')
    submit = SubmitField('Submit')
This code sets up CSRF protection in Flask and creates a form that includes a CSRF token automatically.
Execution Table
StepActionToken GeneratedToken Sent in FormToken ReceivedToken Valid?Result
1User requests form pageYes (new token)Token included in form HTMLN/AN/AForm page sent with token
2User fills form and submitsN/AToken sent with form dataToken received from formCheckedIf valid, process form
3Server verifies tokenN/AN/AToken matches server tokenYesForm data accepted
4Server verifies tokenN/AN/AToken missing or wrongNoRequest rejected with error
💡 Execution stops after form is accepted or rejected based on token validity.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
csrf_tokenNoneGenerated (random string)Sent in formReceived from formValidated or rejected
form_dataNoneNoneUser input + tokenProcessed if token validStored or error
Key Moments - 3 Insights
Why do we need to include the CSRF token in the form?
Including the token in the form (see execution_table step 1) ensures the server can verify the request came from the original site, preventing attackers from forging requests.
What happens if the token is missing or incorrect?
As shown in execution_table step 4, the server rejects the request to protect against unauthorized actions.
Is the CSRF token the same for every user or request?
The token is unique per user session and often per request (step 1), so attackers cannot guess it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the CSRF token first generated?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Check the 'Token Generated' column in the execution_table.
According to variable_tracker, what happens to csrf_token after Step 3?
AIt is discarded
BIt is sent to the user again
CIt is validated or rejected
DIt becomes None
💡 Hint
Look at the 'csrf_token' row and the 'After Step 3' and 'Final' columns.
If the token is missing in the form submission, what does the server do according to execution_table?
ARejects the request with an error
BGenerates a new token and accepts
CProcesses the form normally
DIgnores the token and continues
💡 Hint
See the 'Token Valid?' and 'Result' columns in step 4 of execution_table.
Concept Snapshot
CSRF protection in Flask:
- Server creates a unique token per user session
- Token included as hidden field in forms
- On form submit, server checks token matches
- If valid, process form; if not, reject
- Prevents attackers from forging requests
Full Transcript
CSRF protection works by generating a secret token on the server when a user requests a form page. This token is included inside the form as a hidden field. When the user submits the form, the token is sent back to the server. The server then checks if the token matches the one it created. If the token is valid, the server processes the form data. If the token is missing or incorrect, the server rejects the request to prevent unauthorized actions. This protects users from attackers who try to trick them into submitting forms without their knowledge.

Practice

(1/5)
1. What is the main purpose of CSRF protection in a Flask web application?
easy
A. To speed up the loading time of web pages
B. To encrypt user passwords in the database
C. To prevent attackers from making users perform unwanted actions without their consent
D. To improve the visual design of forms

Solution

  1. Step 1: Understand what CSRF stands for

    CSRF means Cross-Site Request Forgery, which tricks users into submitting unwanted requests.
  2. Step 2: Identify the purpose of CSRF protection

    CSRF protection stops attackers from forcing users to perform actions they did not intend.
  3. Final Answer:

    To prevent attackers from making users perform unwanted actions without their consent -> Option C
  4. Quick Check:

    CSRF protection = prevent unwanted user actions [OK]
Hint: CSRF stops fake actions from attackers using your login [OK]
Common Mistakes:
  • Confusing CSRF with password encryption
  • Thinking CSRF improves page speed
  • Believing CSRF changes form appearance
2. Which of the following is the correct way to enable CSRF protection in a Flask app using Flask-WTF?
easy
A. from flask_wtf import CSRFProtect app = Flask(__name__) csrf = CSRFProtect(app) csrf.init_app(app)
B. from flask_wtf import CSRFProtect csrf = CSRFProtect() app = Flask(__name__)
C. app = Flask(__name__) app.csrf = True
D. from flask_wtf import CSRFProtect csrf = CSRFProtect(app)

Solution

  1. Step 1: Recall Flask-WTF CSRF setup

    You import CSRFProtect and pass the Flask app instance to it to enable protection.
  2. Step 2: Check the options for correct syntax

    from flask_wtf import CSRFProtect csrf = CSRFProtect(app) correctly imports CSRFProtect and initializes it with the app in one step.
  3. Final Answer:

    from flask_wtf import CSRFProtect csrf = CSRFProtect(app) -> Option D
  4. Quick Check:

    CSRFProtect(app) initializes protection [OK]
Hint: Initialize CSRFProtect with app instance directly [OK]
Common Mistakes:
  • Calling CSRFProtect without passing app
  • Setting app.csrf = True (not valid)
  • Calling init_app after passing app (redundant)
3. Given this Flask route with CSRF protection enabled, what happens if the form is submitted without a CSRF token?
@app.route('/submit', methods=['POST'])
def submit():
    return 'Success'
medium
A. The server raises a CSRF error and rejects the request
B. The server ignores the CSRF token and processes normally
C. The request is accepted and returns 'Success'
D. The server redirects to the home page without error

Solution

  1. Step 1: Understand CSRF token role in POST requests

    CSRF tokens verify that the form submission is from a trusted source.
  2. Step 2: Check behavior when token is missing

    Without a valid CSRF token, Flask-WTF raises an error and rejects the request.
  3. Final Answer:

    The server raises a CSRF error and rejects the request -> Option A
  4. Quick Check:

    Missing CSRF token = error rejection [OK]
Hint: POST without token triggers CSRF error [OK]
Common Mistakes:
  • Assuming request is accepted without token
  • Thinking server silently ignores missing token
  • Believing server redirects instead of error
4. You added CSRF protection to your Flask app but get a 'CSRF token missing' error on form submission. Which fix will solve this issue?
medium
A. Add {{ form.csrf_token }} inside the HTML form
B. Remove the CSRFProtect initialization from the app
C. Change the form method to GET instead of POST
D. Disable CSRF protection in Flask-WTF config

Solution

  1. Step 1: Identify cause of missing CSRF token

    The form must include the CSRF token field to send it with the request.
  2. Step 2: Choose the fix that adds the token to the form

    Adding {{ form.csrf_token }} in the form template includes the token correctly.
  3. Final Answer:

    Add {{ form.csrf_token }} inside the HTML form -> Option A
  4. Quick Check:

    Include CSRF token in form to fix error [OK]
Hint: Always include {{ form.csrf_token }} in your forms [OK]
Common Mistakes:
  • Removing CSRF protection instead of fixing token
  • Changing POST to GET (not secure)
  • Disabling CSRF protection globally
5. You want to protect a Flask route that updates user data via POST. Which combination correctly applies CSRF protection and form token usage?
hard
A. Use CSRFProtect(app) but omit the token in the form for simplicity
B. Enable CSRFProtect(app) and include {{ form.csrf_token }} in the HTML form
C. Skip CSRFProtect and rely on session cookies only
D. Add {{ form.csrf_token }} in form but do not enable CSRFProtect in app

Solution

  1. Step 1: Understand CSRF protection requirements

    Both enabling CSRFProtect in the app and including the token in the form are needed to protect POST routes.
  2. Step 2: Evaluate each option for completeness

    Only Enable CSRFProtect(app) and include {{ form.csrf_token }} in the HTML form correctly enables protection and includes the token in the form.
  3. Final Answer:

    Enable CSRFProtect(app) and include {{ form.csrf_token }} in the HTML form -> Option B
  4. Quick Check:

    Protect POST routes with CSRFProtect and token [OK]
Hint: Both app and form need CSRF setup for protection [OK]
Common Mistakes:
  • Enabling protection but missing token in form
  • Including token but not enabling protection
  • Relying only on session cookies
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard