Skip to content

Minimus CSRF Protection

jefmud edited this page Sep 29, 2022 · 2 revisions

You can use various methods to work on validation of CSRF to protect against cross-site-request forgery. These methods validate the request as being legitimate. Minimus includes rudimentary CSRF protection that is built-in.

(In a future version, it will be modeled somewhat after Django. The Session object will be required, but the function CSRF token can be "called" at the template level and not be passed in the context)

It uses two methods csrf_token(session) and validate_csrf(session) along with the Session to accomplish the task.

NOTE: the token MUST be named csrf_token if you choose to use this validation.

The token is generated by Minimus as 32 random characters and sent to the form as a hidden input in the form. It is then "harvested" along with the form data. The form data is picked up when a "POST" request is made from the client and the tokens are compared.

See below.

app.py

from minimus import Minimus, render_template, Session, csrf_token, validate_csrf, parse_formvars

app = Minimus(__name__)
session = Session(app) # required for CSRF protection

@app.route('/')
def index(env):
    return 'Hello World!'

@app.route('/form', methods=['GET', 'POST'])
def form_view(env):
    
    if env['REQUEST_METHOD'] == 'POST':
        fields = parse_formvars(env) # the csrf is a hidden text field
        if validate_csrf(session, fields['csrf_token']): # now, validate against session
            return 'CSRF token is valid'
        else:
            return 'CSRF token is invalid'

    csrf = csrf_token(session) # serves to 'inject' the token
    return render_template('form_view.html', csrf=csrf) # token must be included to check it

if __name__ == '__main__':
    app.run()

form_view.html

<form action="/form" method="POST">
    <input type="hidden" name="csrf_token" value="{{csrf}}">
    <input type="text" name="name" />
    <input type="submit" value="Submit" />
</form>

Clone this wiki locally