tiangolo / fastapi

FastAPI framework, high performance, easy to learn, fast to code, ready for production
https://fastapi.tiangolo.com/
MIT License
73.21k stars 6.17k forks source link

Add support for csrf tokens in html form with jinja #11657

Closed LainezDev closed 1 month ago

LainezDev commented 1 month ago

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:

from fastapi import FastAPI
from fastapi.middleware.csrf import CSRFMiddleware, csrf_token_processor

app = FastAPI()

your_cookie_name = "your_cookie_name"
your_header_name = "your_header_name"

app.add_middleware(
   CSRFMiddleware, 
   secret = "your_secret",
   cookie_name = your_cookie_name,
   header_name = your_header_name,
   )

templates = Jinja2Templates(
    directory="templates", 
    context_processors=[csrf_token_processor(your_cookie_name, your_header_name)]
    )

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!