Escape
In this step, you will learn how to use escape
for achieving protection from injections attacks.
- Open the
html_escaping.py
file and first import the Flask
class and escape
.
from flask import Flask
from markupsafe import escape
- Next create an instance of the
Flask
class.
app = Flask(__name__)
- 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}"
- 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)
- 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:
- The
<script>
tags are safely displayed as text without being executed as JavaScript, demonstrating the prevention of an XSS attack.