Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 7, 2023 05:20
Show Gist options
  • Save code-boxx/b34438e24214f98fee5c1bd200b9667b to your computer and use it in GitHub Desktop.
Save code-boxx/b34438e24214f98fee5c1bd200b9667b to your computer and use it in GitHub Desktop.
Simple Python Flask CSRF

SIMPLE PYTHON FLASK CSRF

https://code-boxx.com/simple-python-flask-csrf/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a static and templates folder.
    • Move css js files into the static folder.
    • Move html files into the templates folder
    • Create a virtual environment - virtualenv venv.
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install required modules - pip install flask pyjwt bcrypt
    • Run python 2-server.py to start the server.
  2. Access http://localhost in your browser, submit the dummy form.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<title>Dummy Form</title>
<link rel="stylesheet" href="static/x-dummy.css">
</head>
<body>
<form method="post" action="go" target="_blank">
<!-- (A) HIDDEN HTML TOKEN -->
<div>* This token should be hidden in your actual project</div>
<input type="text" name="token" value="{{ token }}">
<!-- (B) FIELDS AS USUAL -->
<input type="email" required name="email" value="jon@doe.com">
<input type="submit" value="GO">
</form>
</body>
</html>
# (A) INITIALIZE
# (A1) LOAD MODULES
from flask import Flask, request, session, render_template
import random, string
# (A2) FLASK INIT
app = Flask(__name__)
app.secret_key = "YOUR_SECRET_KEY"
# app.debug = True
# (A3) SETTINGS
HOST_NAME = "localhost"
HOST_PORT = 80
CSRF_CHAR = 12
# (B) ROUTES
# (B1) DUMMY HTML FORM
@app.route("/")
def index():
session["token"] = "".join(random.choices(string.ascii_uppercase, k=CSRF_CHAR))
return render_template("1-form.html", token=session["token"])
# (B2) SUBMIT FORM
@app.route("/go", methods=["POST"])
def go():
# (B2-1) TOKEN IS NOT "PRIMED"
if ("token" not in session or request.form.get("token") is None):
return "Token mismatch"
# (B2-2) CHECK SUBMITTED TOKEN VS SESSION
if (request.form.get("token") == session["token"]):
# OK - DO YOUR PROCESSING
# REMOVE TOKEN AFTER PROCESSING?
# session.pop("token")
return "It works!"
else:
return "Token mismatch"
# (C) START!
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
md static
md templates
move 1-form.html templates
move x-dummy.css static
virtualenv venv
call venv\Scripts\activate
pip install flask
python 2-server.py
mkdir -m 777 static
mkdir -m 777 templates
mv ./1-form.html ./templates
mv ./x-dummy.css ./static
virtualenv venv
source "venv/Scripts/activate"
pip install flask
python 2-server.py
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
form {
max-width: 500px;
margin: 0 auto;
padding: 20px;
background: #fafafa;
border: 1px solid #ebebeb;
}
input {
width: 100%;
padding: 10px;
}
input[type=text], input[type=email] {
margin-top: 10px;
border: 1px solid #d7d7d7;
}
input[type=submit] {
font-weight: 700;
border: 0;
margin-top: 10px;
color: #fff;
background: #bb1b1b;
cursor: pointer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment