Now FastAPI with support for csrf tokens in html forms with jinja
Added some improvements for using CSRF tokens in HTML forms without affecting the current functionality of the middleware starlette-csrf. The improvement simplifies the process of obtaining the CSRF token by unifying the search logic into a single function _get_submitted_csrf_token. Now, the function will first attempt to obtain the token from the headers, and if it does not find it there, it will search for it in the form. Additionally, this new functionality addresses the crash issue that occurs in Starlette due to body consumption.
This is particularly useful for integration with FastAPI and the development of secure websites utilizing forms.
Now, all that's needed is to add the starlette_csrf middleware and utilize the following template processor in your FastAPI code:
Now, the middleware integrates with a context processor, a function that returns a dictionary containing the CSRF token, CSRF input, and CSRF header for use with other tools such as HTMX.
Simply using {{ csrf_input | safe }} in each form is now sufficient to ensure a more secure web application. For example:
<form method="post">
{{ csrf_input | safe }}
<!-- Other form fields here -->
<button type="submit">Submit</button>
</form>
Furthermore, we can use {{ csrf_header }} in HTMX requests. For example:
<form hx-patch="/route/edit" hx-headers='{{ csrf_header | tojson | safe }}' hx-trigger="submit" hx-target="#yourtarget" hx-swap="outerHTML" >
<!-- Other form fields here -->
<button type="submit">Submit</button>
</form>
Feel free to let me know if you need further adjustments or improvements!
Now FastAPI with support for csrf tokens in html forms with jinja
Added some improvements for using CSRF tokens in HTML forms without affecting the current functionality of the middleware starlette-csrf. The improvement simplifies the process of obtaining the CSRF token by unifying the search logic into a single function _get_submitted_csrf_token. Now, the function will first attempt to obtain the token from the headers, and if it does not find it there, it will search for it in the form. Additionally, this new functionality addresses the crash issue that occurs in Starlette due to body consumption.
This is particularly useful for integration with FastAPI and the development of secure websites utilizing forms.
Now, all that's needed is to add the starlette_csrf middleware and utilize the following template processor in your FastAPI code:
Now, the middleware integrates with a context processor, a function that returns a dictionary containing the CSRF token, CSRF input, and CSRF header for use with other tools such as HTMX.
Simply using {{ csrf_input | safe }} in each form is now sufficient to ensure a more secure web application. For example:
Furthermore, we can use {{ csrf_header }} in HTMX requests. For example:
Feel free to let me know if you need further adjustments or improvements!