Secure HTML Rendering with Flask

Beginner

Introduction

When returning HTML (the default response type in Flask), any user-provided values rendered in the output must be escaped to protect from injection attacks. In this lab, you will learn how to use escape for achieving this. Also HTML templates rendered with Jinja, introduced later, will do this automatically. For now, you can just use escape to do this manually.

Escape

In this step, you will learn how to use escape for achieving protection from injections attacks.

  1. Open the html_escaping.py file and first import the Flask class and escape.
from flask import Flask
from markupsafe import escape
  1. Next create an instance of the Flask class.
app = Flask(__name__)
  1. Then we use the route() decorator to create a route / with a view function called escaping. In the function define a JavaScript code snippet and use escape to render it as text, escape any characters that have special meanings in HTML.
@app.route('/')
def escaping():
    input = "<script>alert('XSS attack');</script>"
    escaped_input = escape(input)
    return f"User input: {escaped_input}"
  1. Creating a main entry point of the script for starting the Flask application at port 5000, enabling the debug mode.
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
  1. To run the application, first using the following commands to launched the Flask application in the terminal:
python3 html_escaping.py

Then open the "Web 5000" tab located at the top of the interface, refresh the page, and you should see the message:
example_image

  • The <script> tags are safely displayed as text without being executed as JavaScript, demonstrating the prevention of an XSS attack.

Summary

In this lab, we have learn how to use escape for manually escaping the input. This can be very useful when deal with potentially harmful attacks. Later we will learn how to render templates with Jinja, which can do this automatically and efficiently.

Other Tutorials you may like