Bird
Raised Fist0
Flaskframework~20 mins

CSRF protection in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
CSRF Protection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
What is the main purpose of CSRF protection in Flask?

CSRF protection is important in web applications. What does it mainly protect against?

AIt validates user input to prevent SQL injection.
BIt encrypts user passwords before storing them in the database.
CIt blocks all external requests to the server.
DIt prevents attackers from tricking users into submitting unwanted requests to a web application.
Attempts:
2 left
💡 Hint

Think about what kind of attack involves making a user unknowingly perform actions.

❓ component_behavior
intermediate
1:30remaining
What happens if a Flask form is submitted without a valid CSRF token?

Consider a Flask app using Flask-WTF with CSRF protection enabled. What is the typical behavior when a form is submitted without a valid CSRF token?

AThe form submission is accepted but logged as suspicious.
BThe server raises a <code>CSRFError</code> and rejects the request.
CThe server ignores the CSRF token and processes the form normally.
DThe server redirects the user to the homepage without processing the form.
Attempts:
2 left
💡 Hint

Think about how Flask-WTF handles invalid CSRF tokens by default.

📝 Syntax
advanced
2:00remaining
Which code snippet correctly adds CSRF protection to a Flask app using Flask-WTF?

Choose the correct code to enable CSRF protection in a Flask app using Flask-WTF.

Flask
from flask import Flask
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

# Add CSRF protection here
A
csrf = CSRFProtect()
csrf.init_app(app)
Bcsrf = CSRFProtect(app)
C
csrf = CSRFProtect(app)
app.config['WTF_CSRF_ENABLED'] = False
D
csrf = CSRFProtect()
app.csrf = csrf
Attempts:
2 left
💡 Hint

Remember that CSRFProtect can be initialized without app and then linked.

🔧 Debug
advanced
2:00remaining
Why does this Flask form raise a CSRF error despite using Flask-WTF?

Given this Flask-WTF form and template, the form submission raises a CSRF error. What is the likely cause?

Flask
class MyForm(FlaskForm):
    name = StringField('Name')
    submit = SubmitField('Submit')

# Template snippet:
# <form method="POST">
#   {{ form.name.label }} {{ form.name() }}
#   {{ form.submit() }}
# </form>
AThe form method should be GET instead of POST.
BThe form class does not inherit from FlaskForm.
CThe form is missing the CSRF token field in the template.
DThe submit button is missing a name attribute.
Attempts:
2 left
💡 Hint

Check if the CSRF token field is included in the HTML form.

❓ state_output
expert
2:30remaining
What is the output of this Flask route with CSRF protection when submitting a form without a token?

Consider this Flask route using Flask-WTF with CSRF protection enabled. What response does the user get if the form is submitted without a CSRF token?

Flask
from flask import Flask, render_template_string
from flask_wtf import FlaskForm
from flask_wtf.csrf import CSRFProtect
from wtforms import StringField, SubmitField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
csrf = CSRFProtect(app)

class TestForm(FlaskForm):
    name = StringField('Name')
    submit = SubmitField('Send')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = TestForm()
    if form.validate_on_submit():
        return 'Form submitted'
    return render_template_string('''
        <form method="POST">
            {{ form.csrf_token }}
            {{ form.name.label }} {{ form.name() }}
            {{ form.submit() }}
        </form>
    ''', form=form)

# If a POST request is sent without CSRF token, what happens?
AThe server returns a 400 Bad Request error with a CSRF error message.
BThe server accepts the form and returns 'Form submitted'.
CThe server redirects to the GET route without error.
DThe server crashes with an unhandled exception.
Attempts:
2 left
💡 Hint

Think about how Flask-WTF handles missing CSRF tokens on POST requests.

Practice

(1/5)
1. What is the main purpose of CSRF protection in a Flask web application?
easy
A. To prevent unauthorized commands from being transmitted from a user the website trusts
B. To speed up the loading time of web pages
C. To encrypt user passwords in the database
D. To improve the visual design of forms

Solution

  1. Step 1: Understand CSRF meaning

    CSRF stands for Cross-Site Request Forgery, which tricks users into submitting unwanted actions.
  2. Step 2: Identify CSRF protection goal

    Protection stops fake requests that appear to come from trusted users, preventing unauthorized actions.
  3. Final Answer:

    To prevent unauthorized commands from being transmitted from a user the website trusts -> Option A
  4. Quick Check:

    CSRF protection = prevent fake trusted requests [OK]
Hint: CSRF stops fake form submissions from trusted users [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?
easy
A. app = Flask(__name__) app.secret_key = 'secret' csrf = CSRFProtect(app)
B. app = Flask(__name__) csrf = CSRFProtect() app.secret_key = 'secret'
C. app = Flask(__name__) csrf = CSRFProtect(app) app.secret_key = None
D. app = Flask(__name__) app.secret_key = None csrf = CSRFProtect(app)

Solution

  1. Step 1: Set secret key before CSRFProtect

    CSRF protection requires a secret key set on the Flask app for token generation.
  2. Step 2: Initialize CSRFProtect with app

    Passing the app instance to CSRFProtect enables protection on the app.
  3. Final Answer:

    app = Flask(__name__) app.secret_key = 'secret' csrf = CSRFProtect(app) -> Option A
  4. Quick Check:

    Secret key set + CSRFProtect(app) = correct setup [OK]
Hint: Set secret_key before CSRFProtect(app) call [OK]
Common Mistakes:
  • Not setting secret_key or setting it after CSRFProtect
  • Passing no app to CSRFProtect
  • Setting secret_key to None disables protection
3. Given this Flask form code snippet, what happens if the CSRF token is missing or invalid when submitting the form?
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField

class MyForm(FlaskForm):
    name = StringField('Name')
    submit = SubmitField('Send')
medium
A. The form submission is accepted without any error
B. The form automatically regenerates a new CSRF token and retries
C. A CSRFError is raised and the request is rejected
D. The form data is saved but a warning is logged

Solution

  1. Step 1: Understand FlaskForm CSRF behavior

    FlaskForm automatically checks for a valid CSRF token on submission.
  2. Step 2: Effect of missing/invalid token

    If the token is missing or wrong, Flask-WTF raises a CSRFError and rejects the request.
  3. Final Answer:

    A CSRFError is raised and the request is rejected -> Option C
  4. Quick Check:

    Invalid CSRF token = CSRFError raised [OK]
Hint: Missing CSRF token causes error and blocks form [OK]
Common Mistakes:
  • Assuming form submits anyway without token
  • Thinking token regenerates automatically on failure
  • Believing data saves with just a warning
4. You added CSRFProtect to your Flask app but still get CSRF errors on form submission. Which of these is the most likely cause?
medium
A. You called csrf = CSRFProtect(app) before creating the Flask app
B. You set app.secret_key to a strong random value
C. You used FlaskForm instead of plain WTForms Form
D. You forgot to include {{ form.csrf_token }} inside your HTML form

Solution

  1. Step 1: Check CSRF token inclusion in form

    The CSRF token must be included in the HTML form using {{ form.csrf_token }} for validation.
  2. Step 2: Understand error cause

    If the token is missing in the form, the server rejects the submission with a CSRF error.
  3. Final Answer:

    You forgot to include {{ form.csrf_token }} inside your HTML form -> Option D
  4. Quick Check:

    Missing token in form = CSRF errors [OK]
Hint: Always add {{ form.csrf_token }} inside your form tag [OK]
Common Mistakes:
  • Assuming secret_key causes errors when set correctly
  • Thinking FlaskForm causes errors instead of helping
  • Initializing CSRFProtect before app creation causes syntax error, not CSRF error
5. You want to protect an API endpoint in Flask that accepts JSON POST requests from your frontend. Which approach correctly applies CSRF protection?
hard
A. Disable CSRF protection for JSON endpoints because tokens only work with HTML forms
B. Use CSRFProtect and require the frontend to send the CSRF token in a custom header, then validate it in Flask
C. Add {{ form.csrf_token }} in the JSON payload sent by the frontend
D. Use FlaskForm on the API endpoint without any token validation

Solution

  1. Step 1: Understand CSRF with JSON APIs

    CSRF tokens can protect JSON POST requests if the token is sent in headers and validated server-side.
  2. Step 2: Correct method to protect API

    Use CSRFProtect and require frontend to send token in a custom header (e.g., X-CSRFToken), then validate it in Flask.
  3. Final Answer:

    Use CSRFProtect and require the frontend to send the CSRF token in a custom header, then validate it in Flask -> Option B
  4. Quick Check:

    CSRF token in header + validation = secure JSON API [OK]
Hint: Send CSRF token in header for JSON API protection [OK]
Common Mistakes:
  • Thinking CSRF tokens only work with HTML forms
  • Putting CSRF token inside JSON body without validation
  • Using FlaskForm without token validation on APIs
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