Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds support for csrf tokens in html forms #18

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

LainezDev
Copy link

@LainezDev LainezDev commented May 28, 2024

Starlette CSRF Middleware with html forms

Added some small improvements for using CSRF tokens in HTML forms without affecting the current functionality of the middleware. 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:

import typing
from fastapi.templating import Jinja2Templates
from fastapi import Request
from app.core.config import settings

def csrf_token_processor(request: Request)  -> typing.Dict[str, typing.Any]:
    csrf_token = request.cookies.get(settings.CSRF_COOKIE_NAME)
    csrf_input = f'<input type="hidden" name="{settings.CSRF_COOKIE_NAME}" value="{csrf_token}">'
    csrf_header = {settings.CSRF_HEADER_NAME: csrf_token}
    return {
        'csrf_token': csrf_token,
        'csrf_input': csrf_input,
        'csrf_header': csrf_header 
        }

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

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>

@LainezDev LainezDev changed the title new functionality for handling csrf tokens in html forms adds support for csrf tokens in html forms May 29, 2024
@LainezDev LainezDev changed the title adds support for csrf tokens in html forms Adds support for csrf tokens in html forms May 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant