# csrf middleware ```python from spiderweb import SpiderwebRouter app = SpiderwebRouter( middleware=[ "spiderweb.middleware.sessions.SessionMiddleware", "spiderweb.middleware.csrf.CSRFMiddleware", ], ) ``` Cross-site request forgery, put simply, is a method for attackers to make legitimate-looking requests in your name to a service or system that you've previously authenticated to. Ways that we can protect against this involve aggressively expiring session cookies, special IDs for forms that are keyed to a specific user, and more. > [!TIP] > Notice that in the example above, SessionMiddleware is also included in the middleware list. The CSRF middleware requires the SessionMiddleware to function, and SessionMiddleware must be placed above it in the middleware list. ## CSRF and Forms When you create a form, submitting data to the form is the part where things can go wrong. The CSRF middleware grants you two extra pieces in the TemplateResponse response: `csrf_token` and `csrf_token_raw`. `csrf_token` is a preformatted HTML input with preset attributes, ready for use, that you can drop into your template, while `csrf_token_raw` is the token itself with no extra formatting in case you'd like to do something else with it. Here's an example app that renders a form with two input fields and a checkbox, accepts the form data, and sends back the information as JSON. ```python # myapp.py from spiderweb import SpiderwebRouter from spiderweb.response import JsonResponse, TemplateResponse app = SpiderwebRouter( templates_dirs=["templates"], middleware=[ "spiderweb.middleware.sessions.SessionMiddleware", "spiderweb.middleware.csrf.CSRFMiddleware", ], ) @app.route("/", allowed_methods=["GET", "POST"]) def form(request): if request.method == "POST": return JsonResponse(data=request.POST) else: return TemplateResponse(request, "form.html") ``` ```html