Bird
0
0

You want to add multiple secure headers in Flask, but only for HTTPS requests. Which is the best way to do this securely and efficiently?

hard📝 Application Q15 of 15
Flask - Security Best Practices
You want to add multiple secure headers in Flask, but only for HTTPS requests. Which is the best way to do this securely and efficiently?
AUse <code>@app.after_request</code> to check <code>request.is_secure</code> and add headers conditionally
BAdd headers in each route function only if <code>request.scheme == 'https'</code>
CSet headers globally without checking protocol, assuming HTTPS everywhere
DUse <code>@app.before_request</code> to add headers before response is created
Step-by-Step Solution
Solution:
  1. Step 1: Understand when headers should be added

    Secure headers like Strict-Transport-Security should only be sent over HTTPS to avoid security risks.
  2. Step 2: Choose the best place to add headers conditionally

    @app.after_request runs after response creation and can access request.is_secure to conditionally add headers efficiently for all routes.
  3. Step 3: Evaluate other options

    Adding headers in each route duplicates code; setting headers globally without checking protocol risks sending them over HTTP; @app.before_request cannot modify response headers.
  4. Final Answer:

    Use @app.after_request to check request.is_secure and add headers conditionally -> Option A
  5. Quick Check:

    Conditional header addition in @app.after_request is best [OK]
Quick Trick: Check request.is_secure in @app.after_request [OK]
Common Mistakes:
MISTAKES
  • Adding headers in each route causing repetition
  • Sending secure headers over HTTP by default
  • Trying to set headers in @app.before_request which can't modify response

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes